@promptctl/cc-candybar 1.156.1 → 1.156.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +96 -96
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.156.1`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`4bdc3df37f8c755cdaf7bd87d774300df81f89e6861db8f723f956f1593c458c`}function Ze(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:$e(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:$e(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function O(e,t,n){let r=pt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
2
|
+
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.156.2`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`bb5bee22ef7474a7052967a8afef6457eceba4f2745c1733136de53ae4634055`}function Ze(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:$e(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:$e(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function O(e,t,n){let r=pt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
3
3
|
`)}function Wt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Mt.filter(e=>t[e]!==void 0);return n.every(e=>Gt(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function A(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Pt.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function Gt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Kt(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const qt=1e4;function Jt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>qt?qt:t}function Yt(e){return typeof e==`boolean`?e:void 0}function Xt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var j=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Zt(e){return Qt(JSON.stringify(e))}function Qt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function $t(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new j(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new j(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function en(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=$t(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(Zt(t))})}function tn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Gt(n);return It.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function nn(e,t,n){let r=null;try{r=await cn(vt(),t.connectMs);let i=await en(r,{v:3,...e},t.budgetMs);return on(e.kind,i,n)}catch(e){return sn(e)}finally{r&&r.destroy()}}function rn(e,t){return typeof e==`string`?e:t}function an(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function on(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=rn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:an(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function sn(e){if(e instanceof j||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function cn(e,t){return new Promise((n,r)=>{let i=E.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function ln(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const un={connectMs:50,budgetMs:150},dn={connectMs:50,budgetMs:200};function fn(e){let t=e.output;return typeof t==`string`?t:void 0}function pn(e){return on(`render`,e,fn)}function mn(e,t,n,r){return nn({kind:`render`,hookData:e,args:t,cwd:n,...r},un,fn)}function hn(e,t){return nn({kind:`pane-session`,socket:e,pane:t},dn,e=>`paneSession`in e?e.paneSession:void 0)}function gn(e,t){return nn({kind:`click`,verb:e,value:t,clientVersion:qe},dn,fn)}let _n=null;function vn(e){if(_n!==null)return _n;p.mkdirSync(s.dirname(e),{recursive:!0});try{_n=p.statSync(e).size}catch{_n=0}return _n}function yn(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,r=`${e}.${t+1}`;try{p.renameSync(n,r)}catch{}}try{p.renameSync(e,`${e}.1`)}catch{}_n=0}function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=jt(),t=vn(e);p.appendFileSync(e,n),_n=t+Buffer.byteLength(n,`utf8`),_n>=5242880&&yn(e)}catch(e){_n=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const bn=5e3;function xn(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
4
4
|
`)}const Sn=`/usr/bin/footprint`;function Cn(e,t){return e===`darwin`?[En(Sn,[`-p`,String(t)]),En(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Dn(`/proc/self/smaps_rollup`),Dn(`/proc/self/status`)]:[]}function wn(e,t){return e===`darwin`?Tn(t,e=>lt({bin:Sn,args:e,timeoutMs:bn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Tn(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${On(r.stderr)}`};let i=N(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function N(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function En(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=ut({bin:e,args:[...t],timeoutMs:bn,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${On(n.stderr)}`}}}}function Dn(e){return{name:e,read:()=>{try{let t=p.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function On(e){let t=e.split(`
|
|
5
5
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const kn=`CC_CANDYBAR_RSS_LIMIT_MB`;function An(e){let t=e[kn];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${kn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function jn(e){return An(e)*2}const Mn=1024*1024,Nn=e=>Math.round(e/Mn);function Pn(e){return An(e)*Mn}const Fn={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function In(e,t){return e>t}function Ln(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}function Rn(e,t){return e>t*.75}function zn(e,t,n){let{prefix:r,suffix:i}=Fn[t];return s.join(e,`${r}${n}${i}`)}function Bn(e){for(let t of Object.keys(Fn)){let{prefix:n,suffix:r}=Fn[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Vn(e){let t=e.limitBytes??512*Mn,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null;function o(){return a??=s().finally(()=>{a=null}),a}async function s(){if(r)return!0;let{rss:a,heapTotal:o}=e.memoryBytes(),s=Ln(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${Wn(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${Hn(s)} > limit ${Nn(t)} MB (rss ${Nn(a)} MB, v8 heap ${Nn(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return Gn(e.log,`memory report`,()=>{let t=zn(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Gn(e.log,`heap snapshot`,()=>{let t=zn(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Gn(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of Kn(e.listArtifacts()).slice(n))for(let n of Object.values(t))Gn(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&Rn(i.charge.bytes,t)?`${Hn(i.charge)} approaching limit ${Nn(t)} MB (v8 heap ${Nn(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:Kn(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function u(t=6e4){let n,r=!0,i=async()=>{try{if(await o())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}r&&(n=setTimeout(()=>void i(),t),n.unref())};return i(),{disarm:()=>{r=!1,clearTimeout(n)}}}return{check:o,describeNextRestart:c,serving:l,arm:u}}function Hn(e){return e.kind===`charged`?`${e.measure} ${Nn(e.bytes)} MB`:`rss ${Nn(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Nn(e.gap)} MB gap`} (standing in: ${e.unread})`}function Un(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Wn({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Nn(e.gap)}MB`:``;return`measure=${Un(e)} charge=${Nn(e.bytes)}MB rss=${Nn(t)}MB heap=${Nn(n)}MB limit=${Nn(r)}MB${i}`}function Gn(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Kn(e){let t=new Map;for(let n of e){let e=s.basename(n),r=Bn(e);if(r===null)continue;let{prefix:i,suffix:a}=Fn[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Fn);return[...t].sort(([e],[t])=>In(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function qn(e,t,n={}){let r=_t();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:wn(process.platform,process.pid),captureMemoryReport:()=>xn(Cn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>se.writeHeapSnapshot(e),listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Bn(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function Jn(e={}){if(ur()!==null)return;let n=e.spawn??dr,r=sr();if(r.kind===`contended`){let e=Xn();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Yn(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Yn(n);return}try{Yn(n)}finally{lr()}}function Yn(e){rr()&&Zn(e)}function Xn(){try{let e=p.statSync(Dt());return Date.now()-e.mtimeMs}catch{return null}}function Zn(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -48,39 +48,39 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
48
48
|
`,this._tabSize=hs(t?.tabSize??8),this._noWrap=t?.noWrap??!1}get plain(){return this._text}set plain(e){let t=ld(e);this._text=t;let n=t.length;this._spans=this._spans.map(e=>e.end>n?new yd(e.start,Math.min(e.end,n),e.style):e).filter(e=>e.start<n)}get length(){return this._text.length}get cellLength(){return Zo(gs(this._text,this._tabSize).text)}get hasContent(){return this._text.length>0}get style(){return this._style}set style(e){this._style=md(e)}get justify(){return this._justify}set justify(e){this._justify=e}get overflow(){return this._overflow}set overflow(e){this._overflow=e}get end(){return this._end}set end(e){this._end=e}get noWrap(){return this._noWrap}set noWrap(e){this._noWrap=e}get spans(){return this._spans}resolvedStyle(e){return _d(e,this._style)}edgeStyle(e,t){let n=this.resolvedStyle(t);if(this._text.length===0)return n;let r=e===`left`?0:this._text.length-1,i=n;for(let e of this._spans)e.start<=r&&r<e.end&&(i=i.add(_d(t,e.style)));return i}append(t,n){if(t instanceof e){if(n!==void 0)throw Error(`Style argument must not be provided when appending RichText`);let e=this._text.length;this._text+=t._text,this._addSpan(e,this._text.length,t._style);for(let n of t._spans)this._spans.push(n.move(e));return this}let r=ld(t),i=this._text.length;return this._text+=r,this._addSpan(i,this._text.length,n??``),this}contains(t){let n=t instanceof e?t._text:t;return this._text.includes(n)}at(t){let n=t<0?this._text.length+t:t;return this._text[n]===void 0?new e(``):this.slice(n,n+1)}slice(e,t){let n=this._text,r=n.length,i=e??0,a=t??r,o=i<0?Math.max(0,r+i):Math.min(i,r),s=a<0?Math.max(0,r+a):Math.min(a,r);if(o>=s)return this.blankCopy();let c=n.slice(o,s),l=this.blankCopy(c);for(let e of this._spans){let t=Math.max(e.start,o)-o,n=Math.min(e.end,s)-o;t<n&&l._spans.push(new yd(t,n,e.style))}return l}_addSpan(e,t,n){let r=md(n);gd(r)||this._spans.push(new yd(e,t,r))}stylize(e,t,n){let r=this._text.length,i=t===void 0?0:t<0?r+t:t,a=n===void 0?r:n<0?r+n:n;if(i>=a||i>=r||a<=0)return this;let o=Math.max(0,i),s=Math.min(r,a);return this._addSpan(o,s,e),this}highlightRegex(e,t){let n=this._text,r=0,i=e.flags.includes(`g`)?e.flags:e.flags+`g`,a=new RegExp(e.source,i),o;for(;(o=a.exec(n))!==null;){if(o[0].length===0){a.lastIndex++;continue}if(o.groups){let e=0;for(let[t,n]of Object.entries(o.groups))if(n!==void 0){let r=o[0].indexOf(n,e);if(r>=0){let i=o.index+r;this._addSpan(i,i+n.length,t),e=r+n.length}}r++;continue}this._addSpan(o.index,o.index+o[0].length,t??``),r++}return r}highlightWords(e,t,n){let r=n?.caseSensitive!==!1,i=0;for(let n of e){if(n.length===0)continue;let e=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=r?`g`:`gi`,o=RegExp(`\\b${e}\\b`,a),s;for(;(s=o.exec(this._text))!==null;)this._addSpan(s.index,s.index+s[0].length,t),i++}return i}copy(){let t=new e(this._text,{style:this._style,justify:this._justify,overflow:this._overflow,end:this._end,tabSize:this._tabSize,noWrap:this._noWrap});return t._spans=this._spans.slice(),t}blankCopy(t){return new e(t??``,{style:this._style,justify:this._justify,overflow:this._overflow,end:this._end,tabSize:this._tabSize,noWrap:this._noWrap})}split(e){let t=e??`
|
|
49
49
|
`,n=this._text,r=[],i=0;for(;;){let e=n.indexOf(t,i);if(e===-1){r.push(this.slice(i));break}r.push(this.slice(i,e)),i=e+t.length}return r}divide(e){if(e.length===0)return[this.copy()];let t=[],n=0;for(let r of e)t.push(this.slice(n,r)),n=r;return t.push(this.slice(n)),t}rstrip(){let e=this._text.replace(/\s+$/,``);return e.length<this._text.length&&(this.plain=e),this}pad(e,t){let n=ld(t??` `).repeat(e);return this._spans=this._spans.map(e=>e.move(n.length)),this._text=n+this._text+n,this}expandTabs(){let e=gs(this._text,this._tabSize);return this._spans=this._spans.map(t=>new yd(e.offsetOf(t.start),e.offsetOf(t.end),t.style)),this._text=e.text,this}padLeft(e,t){let n=ld(t??` `).repeat(e);return this._spans=this._spans.map(e=>e.move(n.length)),this._text=n+this._text,this}padRight(e,t){return this._text+=ld(t??` `).repeat(e),this}setLength(e){return this._text.length<e?this._text+=` `.repeat(e-this._text.length):this._text.length>e&&(this.plain=this._text.slice(0,e)),this}extendStyle(e){let t=this._text.length;return this._text+=` `.repeat(e),this._spans=this._spans.map(n=>n.end===t?n.extend(e):n),this}truncate(e,t){if(this.cellLength<=e)return this;this.expandTabs();let n=t?.mode??`right`,r=es(e),i=us(ld(t?.marker??`…`),r),a=Qo(r-Zo(i));if(n===`right`)return this._cropRightTo(a),i&&(this._text+=i),this;if(n===`left`)return this._cropLeftTo(a),i&&(this._spans=this._spans.map(e=>e.move(i.length)),this._text=i+this._text),this;let o=Qo(Math.floor(a/2)),s=Qo(a-o),c=us(this._text,o).length,l=this._text.length-ds(this._text,s).length,u=this._text.slice(0,c),d=this._text.slice(l),f=c,p=l,m=i.length-(p-f),h=[];for(let e of this._spans)e.end<=f?h.push(e):e.start>=p?h.push(e.move(m)):(e.start<f&&h.push(new yd(e.start,f,e.style)),e.end>p&&h.push(new yd(p+m,e.end+m,e.style)));return this._text=u+i+d,this._spans=h,this}_cropRightTo(e){this.plain=us(this._text,e)}_cropLeftTo(e){let t=this._text.length-ds(this._text,e).length,n=-t;this._spans=this._spans.map(e=>{if(!(e.end<=t))return new yd(Math.max(0,e.start+n),e.end+n,e.style)}).filter(e=>e!==void 0),this._text=this._text.slice(t)}align(e,t){let n=this.cellLength;if(n>=t)return this;this.expandTabs();let r=t-n;switch(e){case`left`:this.padRight(r);break;case`right`:this.padLeft(r);break;case`center`:{let e=Math.floor(r/2),t=r-e;this.padLeft(e),this.padRight(t);break}}return this}removeSuffix(e){return this._text.endsWith(e)&&(this.plain=this._text.slice(0,-e.length)),this}appendTokens(e){for(let[t,n]of e)this.append(t,n);return this}static assemble(t,n){let r=new e(``,{style:n?.style});for(let n of t)if(typeof n==`string`)r.append(n);else if(n instanceof e)r.append(n);else{let[e,t]=n;r.append(e,t)}return r}static styled(t,n){let r=new e(t);return r.stylize(n),r}static fromFragments(t,n){let r=new e(``,{end:n?.end??``});for(let e of t)r.append(e);return r}*render(e){let t=gs(this._text,this._tabSize),n=this.resolvedStyle(e),{segments:r,covered:i}=this._buildSegments(t,n,e),a=bd(r,i);r.push(W.line());let o=W.splitLines(r),s=es(Wu(e,this).maxWidth),c=this._overflow??e.overflow??`fold`,l=this._noWrap||(e.noWrap??!1),u=c===`ignore`?es(1/0):s,d=l?es(1/0):u,f=c===`ignore`?void 0:this._justify??e.justify,p=Ru(e,`…`,`.`);for(let e=0;e<o.length;e+=1){let t=o[e],r=a[e],i=e<o.length-1,l=Qu(dd(t),d,{fold:c===`fold`}),m=W.divide(t,l),h=this._justifyLines(m.map((e,t)=>({segments:[...this._fitLine(e,u,c,p)],free:e=>r(t===0?e:l[t-1]+e)})),s,n,f);for(let e=0;e<h.length;e+=1)yield*h[e],(e<h.length-1||i)&&(yield W.line())}this._end&&(yield new W(this._end))}measure(e){let t=gs(this._text,this._tabSize).text.split(`
|
|
50
50
|
`),n=t.reduce((e,t)=>Math.max(e,Zo(t)),0),r=t.flatMap(Xu),i=r.length>0?r.reduce((e,t)=>Math.max(e,t),0):n,a=es(e.maxWidth);return{minimum:Math.min(i,a),maximum:Math.min(n,a)}}_buildSegments({text:e,offsetOf:t},n,r){let i=n=>Math.max(0,Math.min(t(n),e.length)),a=new Set;for(let e of this._spans)a.add(i(e.start)),a.add(i(e.end));a.delete(0),a.delete(e.length);let o=[0,...[...a].sort((e,t)=>e-t),e.length],s=new Map(o.map((e,t)=>[e,t]).reverse()),c=o.slice(0,-1).map(()=>n),l=c.map(()=>!1);for(let e of this._spans){let t=i(e.end),n=_d(r,e.style),a=s.get(i(e.start));for(let e=a;o[e]<t;e++)c[e]=c[e].add(n),l[e]=!0}return{segments:c.map((t,n)=>new W(e.slice(o[n],o[n+1]),t.isNull?void 0:t)),covered:l}}_justifyLines(e,t,n,r){return r===`full`?e.map(({segments:r},i)=>i===e.length-1?r:this._fillLine(r,t,n)):e.map(e=>[...this._justifyLine(e,t,n,r)])}*_justifyLine({segments:e,free:t},n,r,i){let a=r.isNull?void 0:r;switch(i){case`center`:case`right`:{let r=W.adjustLineLength(e,W.getLineLength(e)-fd(e),void 0,!1),o=Math.max(n-W.getLineLength(r),0),s=i===`center`?Math.floor(o/2):o;yield*xd(r,t,s,o-s,a);break}case`left`:yield*xd(e,t,0,Math.max(n-W.getLineLength(e),0),a);break;default:yield*e;break}}_fillLine(e,t,n){let r=dd(e),i=r.split(` `);r.endsWith(` `)&&i.pop();let a=i.length-1,o=Array(a).fill(1),s=i.reduce((e,t)=>e+Zo(t),0)+a;for(let e=0;s<t&&a>0;e=(e+1)%a)o[a-1-e]+=1,s+=1;let c=[],l=0;for(let e=0;e<i.length;e+=1)l+=Zo(i[e]),c.push(l),l+=1,e<a&&c.push(l);let u=W.divide(e,c),d=(e,t)=>e.filter(e=>e.hasText).at(t)?.style??n,f=[];for(let e=0;e<i.length;e+=1)if(f.push(...u[e*2]),e<a){let t=d(u[e*2],-1),r=d(u[e*2+2],0),i=t.equals(r)?t:n;f.push(new W(` `.repeat(o[e]),i.isNull?void 0:i))}return f}*_fitLine(e,t,n,r){let i=W.getLineLength(e);if(i-fd(e)<=t){yield*W.adjustLineLength(e,Math.min(i,t),void 0,!1);return}if(n===`ellipsis`&&t>0){yield*W.adjustLineLength(e,t-1,void 0,!1),yield new W(r);return}yield*W.adjustLineLength(e,t,void 0,!1)}};function bd(e,t){let n=[[]];return e.forEach((e,r)=>{e.text.split(`
|
|
51
|
-
`).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+Zo(e),free:!t[r]})})}),n.map(e=>t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].end<=t?n=i+1:r=i}return e[n].free})}function*xd(e,t,n,r,i){if(n+r===0)return yield*e;let a=e.filter(e=>e.text!==``),o=e=>` `.repeat(e),s=W.getLineLength(a);if(s===0)return yield new W(o(n+r),i);let c=a.length-1,l=n>0&&a[0].cellLength>0&&t(0),u=r>0&&a[c].cellLength>0&&t(s-1),d=+!!l,f=u?c:c+1;if(d>f){yield new W(o(n)+a[0].text+o(r),i);return}n>0&&(yield new W(o(n)+(l?a[0].text:``),i)),yield*a.slice(d,f),r>0&&(yield new W((u?a[c].text:``)+o(r),i))}const Sd=Object.freeze({name:`join`});var Cd=class{fg;bg;constructor(e,t){this.fg=e,this.bg=t}};function wd(e,t){for(let n=e;n;n=n.inner){if(t.has(n.owner))return{fg:!0,bg:!0};if(n.owner instanceof Cd){let{fg:e,bg:r}=n.owner;return{fg:e!==null&&t.has(e),bg:r!==null&&t.has(r)}}}return{fg:!1,bg:!1}}function Td(e,t,n,r){let i=e.join(t,n,r);return{render:e=>W.anchorLines([[...Hu(i,e)]],Sd)[0]}}function Ed(e){return{render:t=>W.anchorLines([[...Hu(e,t)]],e)[0]}}var Dd=class{items;joiner;constructor(e,t){this.items=e,this.joiner=t}*render(e){let t=this.items;if(t.length===0)return;let n={...e,justify:void 0};yield*Hu(Td(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*Hu(Ed(r),n);let i=e+1<t.length?t[e+1]:null;yield*Hu(Td(this.joiner,r,i,{index:e+1}),n)}yield W.line()}contents(){return this.items}measure(e){let t=0;for(let n of Hu(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const Od=[`seam`,`divider`,`lead`,`tail`];function*kd(e){yield e,`mix`in e&&(yield*kd(e.mix[0]),yield*kd(e.mix[1]))}const Ad=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,jd=(e,t,n,r)=>{let i=Ad(e);return i[Math.floor(parseInt(ed(`${t}:${n}:${r}`),16)/2**32*i.length)]},Md=e=>Zo(Ad(e)[0]??``),Nd=e=>e.reduce((e,t)=>e+Md(t),0);function Pd(e,t,n){if(e===`ground`)return n(`mixes ground, whose colour is unknown`);let r=typeof e==`object`&&e?e:{};if((r.edge===`left`||r.edge===`right`)&&(r.part===`bg`||r.part===`fg`))return r.edge===t&&n(`names the ${t} neighbour, which this part is drawn without`),Object.freeze({edge:r.edge,part:r.part});if(typeof r.role==`string`)return Object.freeze({role:r.role});if(Array.isArray(r.mix)&&r.mix.length===3){let[e,i,a]=r.mix;return(typeof a!=`number`||!(a>=0&&a<=1))&&n(`mixes at ${String(a)}, outside 0..1`),Object.freeze({mix:Object.freeze([Pd(e,t,n),Pd(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const Fd=(e,t,n)=>e===`ground`?e:Pd(e,t,n),Id={seam:void 0,divider:void 0,lead:`left`,tail:`right`},Ld={seam:`seam`,divider:`seam`,lead:`caps`,tail:`caps`};function Rd(e,t,n,r){let i=e.glyph,a=typeof i==`object`&&i?i.oneOf:void 0;typeof i!=`string`&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))&&r(`has a glyph that is neither a string nor a oneOf of strings: ${JSON.stringify(i)}`),e.fg===`ground`&&e.bg===`ground`&&r(`has ground on both sides`);let o=Ad(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>Zo(t)!==Md(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(Lu)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:Fd(e.fg,Id[n],r),bg:Fd(e.bg,Id[n],r)})}function zd(e,t,n,r){let i=e,a=Ld[n];if(typeof i?.[t]!=`object`||i[t]===null)throw Error(`${a}: has no ${t} form`);let o=i[t][n];if(!Array.isArray(o))throw Error(`${a}: ${t} ${n} is not a list of cells`);return Object.freeze(o.map((e,i)=>{let o=e=>{throw Error(`${a}: ${t} ${n}[${i}] ${e}`)};return typeof e==`object`&&e?r(e,o):o(`is not a cell`)}))}const Bd=(e,t)=>(n,r)=>Rd(n,e,t,r),Vd=(e,t)=>(n,r)=>{if(!(`cap`in n))return Rd(n,e,t,r);let{cap:i}=n;return Object.keys(n).length!==1&&r(`names a cap and draws cells of its own; a cell is one or the other`),i===`lead`||i===`tail`?Object.freeze({cap:i}):r(`names a cap that is neither lead nor tail: ${JSON.stringify(i)}`)},Hd=e=>[Nd(e.filter(e=>!(`cap`in e))),e.filter(e=>`cap`in e&&e.cap===`lead`).length,e.filter(e=>`cap`in e&&e.cap===`tail`).length];function Ud(e){let t=t=>{let n=zd(e,t,`seam`,Vd(t,`seam`)),r=e[t].divider===e[t].seam?n:zd(e,t,`divider`,Vd(t,`divider`)),[i,a]=[Hd(n),Hd(r)];if(i.some((e,t)=>e!==a[t]))throw Error(`seam: ${t} divider is not the width of the seam under every caps`);return Object.freeze({seam:n,divider:r})};return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Wd(e){let t=t=>Object.freeze({lead:zd(e,t,`lead`,Bd(t,`lead`)),tail:zd(e,t,`tail`,Bd(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Gd(e,t){let n=e=>e.flatMap(e=>`cap`in e?t[e.cap]:[e]),r=n(e.seam);return{seam:r,divider:e.divider===e.seam?r:n(e.divider),lead:t.lead,tail:t.tail}}const Kd=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...kd(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function qd(e){let t=[...e.seam,...e.divider];return{shape:e,reads:{seam:{left:Kd(t,`left`),right:Kd(t,`right`)},lead:Kd(e.lead,`right`),tail:Kd(e.tail,`left`)}}}function Jd(e){return e!==void 0&&!e.isDefault?e:void 0}function Yd(e){return e.flattenAlpha(Cs)}function Xd(e,t){if(e.reverse)return!1;let{color:n,bgcolor:r}=e.drawnColors(t??z.TRUECOLOR);if(n===void 0||r===void 0)return!1;let i=n.fixedValue,a=r.fixedValue;return i!==void 0&&a!==void 0?V.fromRgba(i).deltaE(V.fromRgba(a))<.04:n.number===void 0?n.name===r.name:n.number===r.number}function Zd(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=Jd(n?.bgcolor);return r&&Yd(r)}if(`role`in e)return zu(n,e.role).color;let[r,i,a]=e.mix,o=Zd(r,t,n),s=Zd(i,t,n);return o&&s&&B.blend(o,s,a)}function Qd(e,t,n){return e.fg===`ground`?new H({color:e.bg===`ground`?void 0:Zd(e.bg,t,n),reverse:!0}):new H({color:Zd(e.fg,t,n),bgcolor:e.bg===`ground`?void 0:Zd(e.bg,t,n)})}const $d=e=>Od.flatMap(t=>e[t].flatMap(Ad)).join(``);var ef=class{seam;caps;_forms;constructor(e,t){this.seam=Ud(e),this.caps=Wd(t),this._forms={glyph:qd(Gd(this.seam.glyph,this.caps.glyph)),ascii:qd(Gd(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{shape:a,reads:o}=Ru(i,r.glyph,r.ascii,e=>$d(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=Jd(s.left?.bgcolor),l=Jd(s.right?.bgcolor),u=e!==null&&(!o.seam.left||c!==void 0),d=t!==null&&(!o.seam.right||l!==void 0),f=d&&(!o.lead||l!==void 0),p=u&&(!o.tail||c!==void 0),m={left:e,right:t},h=e=>e!==`ground`&&`edge`in e?m[e.edge]:null,g=e=>a[e].map((t,r)=>{let a=new Cd(h(t.fg),h(t.bg));return new W(jd(t,e,n,r),Qd(t,s,i).withAnchor({owner:a,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*g(f?`lead`:`tail`));return}let _=g(`seam`);yield*a.divider!==a.seam&&_.every(e=>e.style!==void 0&&Xd(e.style,i.colorSystem))?g(`divider`):_}}}};const tf={edge:`left`,part:`bg`},nf={edge:`right`,part:`bg`},rf={edge:`left`,part:`fg`},af={mix:[tf,nf,1/2]},of=`ground`,sf={cap:`lead`},cf={cap:`tail`},lf=(e,t)=>({glyph:e,ascii:t}),uf={glyph:``,thin:``,ascii:`>`,asciiThin:`>`},df={glyph:``,thin:``,ascii:`/`,asciiThin:`/`},ff={glyph:``,thin:``,ascii:`\\`,asciiThin:`\\`},pf={glyph:``,thin:``,ascii:`}`,asciiThin:`}`},mf={glyph:``,thin:``,ascii:`#`,asciiThin:`>`},hf={glyph:``,thin:``,ascii:`]`,asciiThin:`>`},gf={glyph:``,thin:``,ascii:`)`,asciiThin:`)`},_f=(e,t)=>({seam:[{glyph:e,fg:tf,bg:nf}],divider:[{glyph:t,fg:rf,bg:tf}]}),vf=e=>lf(_f(e.glyph,e.thin),_f(e.ascii,e.asciiThin));function yf(e,t){let n=e=>({mix:[tf,nf,e]}),r={glyph:` `,fg:rf,bg:tf};return{seam:[{glyph:e,fg:tf,bg:n(1/3)},{glyph:e,fg:n(1/3),bg:n(2/3)},{glyph:e,fg:n(2/3),bg:nf}],divider:[r,{glyph:t,fg:rf,bg:tf},r]}}function bf(e){let t=[cf,...e,sf];return{seam:t,divider:t}}function xf(e,t){let n=[{glyph:e,fg:t,bg:af}];return{seam:n,divider:n}}function Sf(e){return{seam:xf({oneOf:e},tf).seam,divider:[{glyph:{oneOf:e},fg:rf,bg:af}]}}const Cf=[{glyph:` | `,fg:{role:`strip.separator`},bg:of}],wf={seam:Cf,divider:Cf},Tf={glyph:` `,fg:rf,bg:of},Ef=e=>({glyph:e,fg:{role:`strip.rail`},bg:of}),Df=Object.freeze({powerline:Ud(vf(uf)),prism:Ud(lf(yf(uf.glyph,uf.thin),yf(uf.ascii,uf.asciiThin))),slant:Ud(vf(df)),backslant:Ud(vf(ff)),flame:Ud(vf(pf)),pixel:Ud(vf(mf)),ice:Ud(vf(hf)),bubble:Ud(vf(gf)),capsule:Ud(lf(bf([Tf]),bf([Tf]))),wrapper:Ud(lf(bf([]),bf([]))),metro:Ud(lf(bf([Ef(`──`)]),bf([Ef(`--`)]))),stitch:Ud(lf(xf(`┊`,rf),xf(`:`,rf))),torn:Ud(lf(Sf([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),Sf([`/\\`,`\\/`]))),plain:Ud(lf(wf,wf))}),Of=e=>lf({lead:[{glyph:e.glyph,fg:of,bg:nf}],tail:[{glyph:e.glyph,fg:tf,bg:of}]},{lead:[],tail:[{glyph:e.ascii,fg:tf,bg:of}]}),kf=(e,t)=>({lead:[{glyph:e,fg:nf,bg:of}],tail:[{glyph:t,fg:tf,bg:of}]}),Af={lead:[],tail:[]},jf=Object.freeze({powerline:Wd(Of(uf)),slant:Wd(Of(df)),backslant:Wd(Of(ff)),flame:Wd(Of(pf)),pixel:Wd(Of(mf)),ice:Wd(Of(hf)),bubble:Wd(Of(gf)),capsule:Wd(lf(kf(``,``),kf(`(`,`)`))),wrapper:Wd(lf(kf(``,``),kf(`<`,`>`))),flat:Wd(lf(Af,Af))}),Mf=Object.freeze({powerline:new ef(Df.powerline,jf.powerline),prism:new ef(Df.prism,jf.powerline),slant:new ef(Df.slant,jf.slant),backslant:new ef(Df.backslant,jf.backslant),flame:new ef(Df.flame,jf.flame),pixel:new ef(Df.pixel,jf.pixel),ice:new ef(Df.ice,jf.ice),bubble:new ef(Df.bubble,jf.bubble),capsule:new ef(Df.capsule,jf.capsule),wrapper:new ef(Df.wrapper,jf.wrapper),metro:new ef(Df.metro,jf.capsule),stitch:new ef(Df.stitch,jf.flat),torn:new ef(Df.torn,jf.flat),plain:new ef(Df.plain,jf.flat)});function Nf(e,t){if(e.isControl)return``;let{text:n,style:r}=e;if(n.length===0||r===void 0)return n;let i=t.colorSystem===null?``:r.toSgrCodes(t.colorSystem),a=i.length>0?`\x1b[${i}m${n}\x1b[0m`:n,o=t.hyperlinks?r.link:void 0;return o===void 0?a:`${id(o)}${a}]8;;\\`}function Pf(e,t){let n=[];for(let r of e)n.push(Nf(r,t));return n.join(``)}const Ff=/\r|\x1b\[([0-9;:]*)m|\x1b\[([012]?)K|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]P_^X][\s\S]*?(?:\x07|\x1b\\|\x9c|$)|\x1b[ -/]*[0-~]/g;function*If(e){let t=0;for(let n of e.matchAll(Ff))n.index>t&&(yield{kind:`text`,text:e.slice(t,n.index)}),n[0]===`\r`&&(yield{kind:`return`}),n[1]!==void 0&&(yield{kind:`sgr`,params:n[1]}),n[2]!==void 0&&(yield{kind:`erase`,mode:n[2]||`0`}),t=n.index+n[0].length;t<e.length&&(yield{kind:`text`,text:e.slice(t)})}function*Lf(e){let t=0;for(let n of sd(e))yield*If(e.slice(t,n.index)),yield{kind:`link`,uri:n.uri},t=n.index+n.length;yield*If(e.slice(t))}function Rf(e){let t=new H(e);return e=>e.add(t)}function zf(e){let t=e.next();return t.done?void 0:t.value}function Bf(e){let t=zf(e);if(t===5){let t=zf(e);return t===void 0?void 0:B.fromAnsi(t)}if(t===2){let[t,n,r]=[zf(e),zf(e),zf(e)];return r===void 0?void 0:B.fromRgb(t,n,r)}}const Vf=new Map([[0,()=>U],...gu.map(e=>[_u[e],Rf({[e]:!0})]),[22,Rf({bold:!1,dim:!1})],[23,Rf({italic:!1})],[24,Rf({underline:!1,underline2:!1})],[25,Rf({blink:!1,blink2:!1})],[27,Rf({reverse:!1})],[28,Rf({conceal:!1})],[29,Rf({strike:!1})],[38,(e,t)=>e.add(new H({color:Bf(t)}))],[39,Rf({color:B.default()})],[48,(e,t)=>e.add(new H({bgcolor:Bf(t)}))],[49,Rf({bgcolor:B.default()})],[58,(e,t)=>(Bf(t),e)],[54,Rf({frame:!1,encircle:!1})],[55,Rf({overline:!1})],...Array.from({length:8},(e,t)=>[[30+t,Rf({color:B.fromAnsi(t)})],[40+t,Rf({bgcolor:B.fromAnsi(t)})],[90+t,Rf({color:B.fromAnsi(t+8)})],[100+t,Rf({bgcolor:B.fromAnsi(t+8)})]]).flat()]),Hf=e=>e;function Uf(e,t){let n=t.split(`;`).filter(e=>/^\d*$/.test(e)).map(e=>Math.min(255,Number(e))).values(),r=e;for(let e of n)r=(Vf.get(e)??Hf)(r,n);return r}const Wf=[` `,U];function Gf(e,t,n){n!==`0`&&e.fill(Wf,0,Math.min(t+1,e.length)),n!==`1`&&(e.length=Math.min(t,e.length))}var Kf=class{sgr=U;link=void 0;decode(e){return(e.match(/[^\n]*\n|[^\n]+/g)??[]).map(e=>this.decodeLine(e.replace(/\r?\n$/,``)))}decodeLine(e){let t=[],n=0;for(let r of Lf(e))switch(r.kind){case`text`:{let e=this.sgr.withLink(this.link);for(let i of r.text)t[n++]=[i,e];break}case`return`:n=0;break;case`erase`:Gf(t,n,r.mode);break;case`sgr`:this.sgr=Uf(this.sgr,r.params);break;case`link`:this.link=r.uri===``?void 0:r.uri;break}let r=[];for(let[e,n]of t){let t=r.at(-1);t?.[1].equals(n)?t[0]+=e:r.push([e,n])}return G.assemble(r)}};function qf(e){return e.end=``,e.plain=e.plain.replaceAll(`
|
|
52
|
-
`,` `),e.expandTabs()}var
|
|
51
|
+
`).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+Zo(e),free:!t[r]})})}),n.map(e=>t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].end<=t?n=i+1:r=i}return e[n].free})}function*xd(e,t,n,r,i){if(n+r===0)return yield*e;let a=e.filter(e=>e.text!==``),o=e=>` `.repeat(e),s=W.getLineLength(a);if(s===0)return yield new W(o(n+r),i);let c=a.length-1,l=n>0&&a[0].cellLength>0&&t(0),u=r>0&&a[c].cellLength>0&&t(s-1),d=+!!l,f=u?c:c+1;if(d>f){yield new W(o(n)+a[0].text+o(r),i);return}n>0&&(yield new W(o(n)+(l?a[0].text:``),i)),yield*a.slice(d,f),r>0&&(yield new W((u?a[c].text:``)+o(r),i))}const Sd=Object.freeze({name:`join`});var Cd=class{fg;bg;constructor(e,t){this.fg=e,this.bg=t}};function wd(e,t){for(let n=e;n;n=n.inner){if(t.has(n.owner))return{fg:!0,bg:!0};if(n.owner instanceof Cd){let{fg:e,bg:r}=n.owner;return{fg:e!==null&&t.has(e),bg:r!==null&&t.has(r)}}}return{fg:!1,bg:!1}}function Td(e,t,n,r){let i=e.join(t,n,r);return{render:e=>W.anchorLines([[...Hu(i,e)]],Sd)[0]}}function Ed(e){return{render:t=>W.anchorLines([[...Hu(e,t)]],e)[0]}}var Dd=class{items;joiner;constructor(e,t){this.items=e,this.joiner=t}*render(e){let t=this.items;if(t.length===0)return;let n={...e,justify:void 0};yield*Hu(Td(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*Hu(Ed(r),n);let i=e+1<t.length?t[e+1]:null;yield*Hu(Td(this.joiner,r,i,{index:e+1}),n)}yield W.line()}contents(){return this.items}measure(e){let t=0;for(let n of Hu(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const Od=[`seam`,`divider`,`lead`,`tail`],kd=.04;function*Ad(e){yield e,`mix`in e&&(yield*Ad(e.mix[0]),yield*Ad(e.mix[1]))}const jd=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,Md=(e,t,n,r)=>{let i=jd(e);return i[Math.floor(parseInt(ed(`${t}:${n}:${r}`),16)/2**32*i.length)]},Nd=e=>Zo(jd(e)[0]??``),Pd=e=>e.reduce((e,t)=>e+Nd(t),0);function Fd(e,t,n){if(e===`ground`)return n(`mixes ground, whose colour is unknown`);let r=typeof e==`object`&&e?e:{};if((r.edge===`left`||r.edge===`right`)&&(r.part===`bg`||r.part===`fg`))return r.edge===t&&n(`names the ${t} neighbour, which this part is drawn without`),Object.freeze({edge:r.edge,part:r.part});if(typeof r.role==`string`)return Object.freeze({role:r.role});if(Array.isArray(r.mix)&&r.mix.length===3){let[e,i,a]=r.mix;return(typeof a!=`number`||!(a>=0&&a<=1))&&n(`mixes at ${String(a)}, outside 0..1`),Object.freeze({mix:Object.freeze([Fd(e,t,n),Fd(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const Id=(e,t,n)=>e===`ground`?e:Fd(e,t,n),Ld={seam:void 0,divider:void 0,lead:`left`,tail:`right`},Rd={seam:`seam`,divider:`seam`,lead:`caps`,tail:`caps`};function zd(e,t,n,r){let i=e.glyph,a=typeof i==`object`&&i?i.oneOf:void 0;typeof i!=`string`&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))&&r(`has a glyph that is neither a string nor a oneOf of strings: ${JSON.stringify(i)}`),e.fg===`ground`&&e.bg===`ground`&&r(`has ground on both sides`);let o=jd(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>Zo(t)!==Nd(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(Lu)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:Id(e.fg,Ld[n],r),bg:Id(e.bg,Ld[n],r)})}function Bd(e,t,n,r){let i=e,a=Rd[n];if(typeof i?.[t]!=`object`||i[t]===null)throw Error(`${a}: has no ${t} form`);let o=i[t][n];if(!Array.isArray(o))throw Error(`${a}: ${t} ${n} is not a list of cells`);return Object.freeze(o.map((e,i)=>{let o=e=>{throw Error(`${a}: ${t} ${n}[${i}] ${e}`)};return typeof e==`object`&&e?r(e,o):o(`is not a cell`)}))}const Vd=(e,t)=>(n,r)=>zd(n,e,t,r),Hd=(e,t)=>(n,r)=>{if(!(`cap`in n))return zd(n,e,t,r);let{cap:i}=n;return Object.keys(n).length!==1&&r(`names a cap and draws cells of its own; a cell is one or the other`),i===`lead`||i===`tail`?Object.freeze({cap:i}):r(`names a cap that is neither lead nor tail: ${JSON.stringify(i)}`)},Ud=e=>[Pd(e.filter(e=>!(`cap`in e))),e.filter(e=>`cap`in e&&e.cap===`lead`).length,e.filter(e=>`cap`in e&&e.cap===`tail`).length];function Wd(e){let t=t=>{let n=Bd(e,t,`seam`,Hd(t,`seam`)),r=e[t].divider===e[t].seam?n:Bd(e,t,`divider`,Hd(t,`divider`)),[i,a]=[Ud(n),Ud(r)];if(i.some((e,t)=>e!==a[t]))throw Error(`seam: ${t} divider is not the width of the seam under every caps`);return Object.freeze({seam:n,divider:r})};return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Gd(e){let t=t=>Object.freeze({lead:Bd(e,t,`lead`,Vd(t,`lead`)),tail:Bd(e,t,`tail`,Vd(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Kd(e,t){let n=e=>e.flatMap(e=>`cap`in e?t[e.cap]:[e]),r=n(e.seam);return{seam:r,divider:e.divider===e.seam?r:n(e.divider),lead:t.lead,tail:t.tail}}const qd=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...Ad(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function Jd(e){let t=[...e.seam,...e.divider];return{shape:e,reads:{seam:{left:qd(t,`left`),right:qd(t,`right`)},lead:qd(e.lead,`right`),tail:qd(e.tail,`left`)}}}function Yd(e){return e!==void 0&&!e.isDefault?e:void 0}function Xd(e){return e.flattenAlpha(Cs)}function Zd(e,t){if(e.reverse)return!1;let{color:n,bgcolor:r}=e.drawnColors(t??z.TRUECOLOR);if(n===void 0||r===void 0)return!1;let i=n.fixedValue,a=r.fixedValue;return i!==void 0&&a!==void 0?V.fromRgba(i).deltaE(V.fromRgba(a))<kd:n.number===void 0?n.name===r.name:n.number===r.number}function Qd(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=Yd(n?.bgcolor);return r&&Xd(r)}if(`role`in e)return zu(n,e.role).color;let[r,i,a]=e.mix,o=Qd(r,t,n),s=Qd(i,t,n);return o&&s&&B.blend(o,s,a)}function $d(e,t,n){return e.fg===`ground`?new H({color:e.bg===`ground`?void 0:Qd(e.bg,t,n),reverse:!0}):new H({color:Qd(e.fg,t,n),bgcolor:e.bg===`ground`?void 0:Qd(e.bg,t,n)})}const ef=e=>Od.flatMap(t=>e[t].flatMap(jd)).join(``);var tf=class{seam;caps;_forms;constructor(e,t){this.seam=Wd(e),this.caps=Gd(t),this._forms={glyph:Jd(Kd(this.seam.glyph,this.caps.glyph)),ascii:Jd(Kd(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{shape:a,reads:o}=Ru(i,r.glyph,r.ascii,e=>ef(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=Yd(s.left?.bgcolor),l=Yd(s.right?.bgcolor),u=e!==null&&(!o.seam.left||c!==void 0),d=t!==null&&(!o.seam.right||l!==void 0),f=d&&(!o.lead||l!==void 0),p=u&&(!o.tail||c!==void 0),m={left:e,right:t},h=e=>e!==`ground`&&`edge`in e?m[e.edge]:null,g=e=>a[e].map((t,r)=>{let a=new Cd(h(t.fg),h(t.bg));return new W(Md(t,e,n,r),$d(t,s,i).withAnchor({owner:a,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*g(f?`lead`:`tail`));return}let _=g(`seam`);yield*a.divider!==a.seam&&_.every(e=>e.style!==void 0&&Zd(e.style,i.colorSystem))?g(`divider`):_}}}};const nf={edge:`left`,part:`bg`},rf={edge:`right`,part:`bg`},af={edge:`left`,part:`fg`},of={mix:[nf,rf,1/2]},sf=`ground`,cf={cap:`lead`},lf={cap:`tail`},uf=(e,t)=>({glyph:e,ascii:t}),df={glyph:``,thin:``,ascii:`>`,asciiThin:`>`},ff={glyph:``,thin:``,ascii:`/`,asciiThin:`/`},pf={glyph:``,thin:``,ascii:`\\`,asciiThin:`\\`},mf={glyph:``,thin:``,ascii:`}`,asciiThin:`}`},hf={glyph:``,thin:``,ascii:`#`,asciiThin:`>`},gf={glyph:``,thin:``,ascii:`]`,asciiThin:`>`},_f={glyph:``,thin:``,ascii:`)`,asciiThin:`)`},vf=(e,t)=>({seam:[{glyph:e,fg:nf,bg:rf}],divider:[{glyph:t,fg:af,bg:nf}]}),yf=e=>uf(vf(e.glyph,e.thin),vf(e.ascii,e.asciiThin));function bf(e,t){let n=e=>({mix:[nf,rf,e]}),r={glyph:` `,fg:af,bg:nf};return{seam:[{glyph:e,fg:nf,bg:n(1/3)},{glyph:e,fg:n(1/3),bg:n(2/3)},{glyph:e,fg:n(2/3),bg:rf}],divider:[r,{glyph:t,fg:af,bg:nf},r]}}function xf(e){let t=[lf,...e,cf];return{seam:t,divider:t}}function Sf(e,t){let n=[{glyph:e,fg:t,bg:of}];return{seam:n,divider:n}}function Cf(e){return{seam:Sf({oneOf:e},nf).seam,divider:[{glyph:{oneOf:e},fg:af,bg:of}]}}const wf=[{glyph:` | `,fg:{role:`strip.separator`},bg:sf}],Tf={seam:wf,divider:wf},Ef={glyph:` `,fg:af,bg:sf},Df=e=>({glyph:e,fg:{role:`strip.rail`},bg:sf}),Of=Object.freeze({powerline:Wd(yf(df)),prism:Wd(uf(bf(df.glyph,df.thin),bf(df.ascii,df.asciiThin))),slant:Wd(yf(ff)),backslant:Wd(yf(pf)),flame:Wd(yf(mf)),pixel:Wd(yf(hf)),ice:Wd(yf(gf)),bubble:Wd(yf(_f)),capsule:Wd(uf(xf([Ef]),xf([Ef]))),wrapper:Wd(uf(xf([]),xf([]))),metro:Wd(uf(xf([Df(`──`)]),xf([Df(`--`)]))),stitch:Wd(uf(Sf(`┊`,af),Sf(`:`,af))),torn:Wd(uf(Cf([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),Cf([`/\\`,`\\/`]))),plain:Wd(uf(Tf,Tf))}),kf=e=>uf({lead:[{glyph:e.glyph,fg:sf,bg:rf}],tail:[{glyph:e.glyph,fg:nf,bg:sf}]},{lead:[],tail:[{glyph:e.ascii,fg:nf,bg:sf}]}),Af=(e,t)=>({lead:[{glyph:e,fg:rf,bg:sf}],tail:[{glyph:t,fg:nf,bg:sf}]}),jf={lead:[],tail:[]},Mf=Object.freeze({powerline:Gd(kf(df)),slant:Gd(kf(ff)),backslant:Gd(kf(pf)),flame:Gd(kf(mf)),pixel:Gd(kf(hf)),ice:Gd(kf(gf)),bubble:Gd(kf(_f)),capsule:Gd(uf(Af(``,``),Af(`(`,`)`))),wrapper:Gd(uf(Af(``,``),Af(`<`,`>`))),flat:Gd(uf(jf,jf))}),Nf=Object.freeze({powerline:new tf(Of.powerline,Mf.powerline),prism:new tf(Of.prism,Mf.powerline),slant:new tf(Of.slant,Mf.slant),backslant:new tf(Of.backslant,Mf.backslant),flame:new tf(Of.flame,Mf.flame),pixel:new tf(Of.pixel,Mf.pixel),ice:new tf(Of.ice,Mf.ice),bubble:new tf(Of.bubble,Mf.bubble),capsule:new tf(Of.capsule,Mf.capsule),wrapper:new tf(Of.wrapper,Mf.wrapper),metro:new tf(Of.metro,Mf.capsule),stitch:new tf(Of.stitch,Mf.flat),torn:new tf(Of.torn,Mf.flat),plain:new tf(Of.plain,Mf.flat)});function Pf(e,t){if(e.isControl)return``;let{text:n,style:r}=e;if(n.length===0||r===void 0)return n;let i=t.colorSystem===null?``:r.toSgrCodes(t.colorSystem),a=i.length>0?`\x1b[${i}m${n}\x1b[0m`:n,o=t.hyperlinks?r.link:void 0;return o===void 0?a:`${id(o)}${a}]8;;\\`}function Ff(e,t){let n=[];for(let r of e)n.push(Pf(r,t));return n.join(``)}const If=/\r|\x1b\[([0-9;:]*)m|\x1b\[([012]?)K|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]P_^X][\s\S]*?(?:\x07|\x1b\\|\x9c|$)|\x1b[ -/]*[0-~]/g;function*Lf(e){let t=0;for(let n of e.matchAll(If))n.index>t&&(yield{kind:`text`,text:e.slice(t,n.index)}),n[0]===`\r`&&(yield{kind:`return`}),n[1]!==void 0&&(yield{kind:`sgr`,params:n[1]}),n[2]!==void 0&&(yield{kind:`erase`,mode:n[2]||`0`}),t=n.index+n[0].length;t<e.length&&(yield{kind:`text`,text:e.slice(t)})}function*Rf(e){let t=0;for(let n of sd(e))yield*Lf(e.slice(t,n.index)),yield{kind:`link`,uri:n.uri},t=n.index+n.length;yield*Lf(e.slice(t))}function zf(e){let t=new H(e);return e=>e.add(t)}function Bf(e){let t=e.next();return t.done?void 0:t.value}function Vf(e){let t=Bf(e);if(t===5){let t=Bf(e);return t===void 0?void 0:B.fromAnsi(t)}if(t===2){let[t,n,r]=[Bf(e),Bf(e),Bf(e)];return r===void 0?void 0:B.fromRgb(t,n,r)}}const Hf=new Map([[0,()=>U],...gu.map(e=>[_u[e],zf({[e]:!0})]),[22,zf({bold:!1,dim:!1})],[23,zf({italic:!1})],[24,zf({underline:!1,underline2:!1})],[25,zf({blink:!1,blink2:!1})],[27,zf({reverse:!1})],[28,zf({conceal:!1})],[29,zf({strike:!1})],[38,(e,t)=>e.add(new H({color:Vf(t)}))],[39,zf({color:B.default()})],[48,(e,t)=>e.add(new H({bgcolor:Vf(t)}))],[49,zf({bgcolor:B.default()})],[58,(e,t)=>(Vf(t),e)],[54,zf({frame:!1,encircle:!1})],[55,zf({overline:!1})],...Array.from({length:8},(e,t)=>[[30+t,zf({color:B.fromAnsi(t)})],[40+t,zf({bgcolor:B.fromAnsi(t)})],[90+t,zf({color:B.fromAnsi(t+8)})],[100+t,zf({bgcolor:B.fromAnsi(t+8)})]]).flat()]),Uf=e=>e;function Wf(e,t){let n=t.split(`;`).filter(e=>/^\d*$/.test(e)).map(e=>Math.min(255,Number(e))).values(),r=e;for(let e of n)r=(Hf.get(e)??Uf)(r,n);return r}const Gf=[` `,U];function Kf(e,t,n){n!==`0`&&e.fill(Gf,0,Math.min(t+1,e.length)),n!==`1`&&(e.length=Math.min(t,e.length))}var qf=class{sgr=U;link=void 0;decode(e){return(e.match(/[^\n]*\n|[^\n]+/g)??[]).map(e=>this.decodeLine(e.replace(/\r?\n$/,``)))}decodeLine(e){let t=[],n=0;for(let r of Rf(e))switch(r.kind){case`text`:{let e=this.sgr.withLink(this.link);for(let i of r.text)t[n++]=[i,e];break}case`return`:n=0;break;case`erase`:Kf(t,n,r.mode);break;case`sgr`:this.sgr=Wf(this.sgr,r.params);break;case`link`:this.link=r.uri===``?void 0:r.uri;break}let r=[];for(let[e,n]of t){let t=r.at(-1);t?.[1].equals(n)?t[0]+=e:r.push([e,n])}return G.assemble(r)}};function Jf(e){return e.end=``,e.plain=e.plain.replaceAll(`
|
|
52
|
+
`,` `),e.expandTabs()}var Yf=class{renderable;effect;t;key;theme;constructor(e,t,n){if(this.renderable=e,this.effect=t,!Number.isFinite(n.t))throw RangeError(`Effected needs a finite t, got ${n.t}`);this.t=n.t,this.key=n.key,this.theme=n.theme}render(e){let t=Hu(this.renderable,e);return e.colorSystem===null?t:this._moved(t,e)}*contents(){yield this.renderable}*_moved(e,t){let n=t.colorSystem??z.TRUECOLOR,r=Zf(e,n,this.theme),i=Qf(r),a=this.effect(ep(r,()=>i,n,this.theme));yield*W.applyStyle(this._recolored(i,a.at(this.t),n),new H({nextChange:a.nextChange(this.t)}))}*_recolored(e,t,n){for(let{segment:r,look:i,glyphs:a}of e){if(i===void 0){yield r;continue}let{style:e,wire:o,slots:s,pair:c}=i,{terminal:l}=c,u={fg:c.fg,bg:c.bg},d=[];for(let{glyph:e,cell:r}of a){let i=r===void 0?s:np(t(u,{...r,seed:this.seed(r.row,r.col),terminal:l,reverse:c.reverse}),c.reverse),a=d[d.length-1],f=a!==void 0&&sp(a.colors,i)?a.drawn:this.respec(o,s,i,n);a!==void 0&&ip(a.drawn,f)?(a.text+=e,a.cells+=Zo(e),a.colors=i):d.push({text:e,cells:Zo(e),colors:i,drawn:f})}if(d.every(e=>ip(e.drawn,o))){yield r;continue}let f=0;for(let t of d){let n=e.shiftedBy(f),r=ip(t.drawn,o)?n:n.add(H.fromColor(t.drawn.color,t.drawn.bgcolor));yield new W(t.text,r),f+=t.cells}}}measure(e){return qu.get(e,this.renderable)}static shows(e,t,n,r){let i=np(e,e.reverse),a=rp(i,np(t,e.reverse),n,r);return np({fg:a.fg?.getTruecolor(r,!0)??i.fg,bg:a.bg?.getTruecolor(r,!1)??i.bg},e.reverse)}respec(e,t,n,r){let i=rp(t,n,r,this.theme);return{color:i.fg??e.color,bgcolor:i.bg??e.bgcolor}}seed(e,t){return Number.parseInt(ed(`${this.key}:${e}:${t}`),16)/4294967296}};const Xf=B.default();function Zf(e,t,n){return[...e].map(e=>{if(e.isControl)return{segment:e,look:void 0};let r=e.style??H.null(),i=r.drawnColors(t),a={fg:(i.color??Xf).getTruecolor(n,!0),bg:(i.bgcolor??Xf).getTruecolor(n,!1)},o=r.reverse===!0,s=np({fg:i.color?.isDefault??!0,bg:i.bgcolor?.isDefault??!0},o);return{segment:e,look:{style:r,wire:i,slots:a,pair:{...np(a,o),terminal:s,reverse:o}}}})}function Qf(e){let t=0,n=0;return e.map(({segment:e,look:r})=>{if(r===void 0)return{segment:e,look:r,glyphs:[]};let i=r.style.anchor,a=0;return{segment:e,look:r,glyphs:[...cs(e.text)].map(e=>{let r=e===`
|
|
53
53
|
`?void 0:{row:t,col:n,anchor:i&&mu(i,a)};return[t,n]=e===`
|
|
54
|
-
`?[t+1,0]:[t,n+Zo(e)],a+=Zo(e),{glyph:e,cell:r}})}})}function Qf(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function $f(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||Qf(e.style);return t.flatMap(({glyph:e,cell:t})=>t!==void 0&&(e.trim()!==``||n)?[t]:[])}),s=e.flatMap(({segment:e,look:t})=>t!==void 0&&e.text.trim()!==``&&!hu(t.style.anchor,Sd)?[t.pair]:[]),c=[...new Map(s.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],l=e=>c.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{cells:()=>a??=o(),pairs:c,colors:new Set([...l(`fg`),...l(`bg`)]),fills:new Set(l(`bg`)),depth:n,theme:r}}function ep(e,...t){let n=new Set(t),r=e=>wd(e.anchor,n),i=({fg:e,bg:t})=>e||t,a=e=>({...e,cells:()=>e.cells().filter(e=>i(r(e)))});return t=>au.map(e(a(t)),e=>(t,n)=>{let a=r(n);if(!i(a))return t;let o=e(t,n);return{fg:a.fg?o.fg:t.fg,bg:a.bg?o.bg:t.bg}})}function tp(e,t){return t?{fg:e.bg,bg:e.fg}:e}function np(e,t,n,r){let i=t.bg.compositeOver(Cs),a=t.fg.compositeOver(i);return{fg:B.matchMove(e.fg,a,n,r,!0),bg:B.matchMove(e.bg,i,n,r,!1)}}function rp(e,t){return ip(e.color,t.color,!0)&&ip(e.bgcolor,t.bgcolor,!1)}function ip(e,t,n){return e===t||ap(e,n)===ap(t,n)}function ap(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function op(e,t){return sp(e.fg,t.fg)&&sp(e.bg,t.bg)}function sp(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const cp=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),lp=e=>e*e*e*(e*(e*6-15)+10),up=(e,t,n)=>e+n*(t-e);function dp(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function fp(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=lp(e),u=lp(t),d=lp(n),f=cp[o]+s,p=cp[f]+c,m=cp[f+1]+c,h=cp[o+1]+s,g=cp[h]+c,_=cp[h+1]+c;return up(up(up(dp(cp[p],e,t,n),dp(cp[g],e-1,t,n),l),up(dp(cp[m],e,t-1,n),dp(cp[_],e-1,t-1,n),l),u),up(up(dp(cp[p+1],e,t,n-1),dp(cp[g+1],e-1,t,n-1),l),up(dp(cp[m+1],e,t-1,n-1),dp(cp[_+1],e-1,t-1,n-1),l),u),d)}function pp(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*fp(e*r,t*r,n*r),o+=a,a/=2}return i/o}function mp(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function hp(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const gp=Array.from({length:48},(e,t)=>(t+1)/48);function _p(e,t){return Math.min(Ts(e.fg,e.bg),4.5)-(t===z.TRUECOLOR?.01:0)}const vp=[`fg`,`bg`];function yp({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>vp.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>V.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=vp.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=_p(r,t),c=(t,n)=>Ep(i,r[t],(t===a?e:o)*n);return gp.every(e=>{let i=Jf.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return Ts(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function bp(e,t){let n=new WeakMap;return wp(Cp(e,r=>{let i=t??r.colors,a=[xp(r),`|`,...i].join(` `),o=n.get(r.theme)??new Go;return n.set(r.theme,o),o.get(a,()=>yp(r,i,e.touch))}))}function xp({depth:e,pairs:t}){return[e,...t.map(Sp)].join(` `)}function Sp({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function Cp(e,t){return n=>{let r=t(n);return au.continuous(t=>{let i=e.field(t,n);return({fg:t,bg:n},a)=>{let o=Math.round(Ap(i(a))*48)/48,s=(t,n)=>Ep(e.touch,t,(n?0:r.get(t.hex)??0)*o);return{fg:s(t,a.terminal.fg),bg:s(n,a.terminal.bg)}}})}}function wp(e){return t=>Tp(t.depth)?au.constant(e=>e):e(t)}function Tp(e){switch(e){case z.DEFAULT:case z.STANDARD:case z.WINDOWS:return!0;case z.EIGHT_BIT:case z.TRUECOLOR:return!1}}function Ep(e,t,n){return n===0?t:e(t,n)}function Dp(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}const Op={shimmer:{seconds:109,ease:ql.linear,swing:.9},pulse:{seconds:43,ease:ql.linear,swing:.85},sparkle:{seconds:139,ease:ql.linear,swing:.95},wheel:{seconds:907,ease:ql.linear,swing:1},fade:{seconds:20,ease:ql[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:ql[`ease-in-out`],swing:1}},kp={sun:new R(255,228,176),firefly:new R(222,245,140)},Ap=e=>Math.min(1,Math.max(0,e));function jp(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new V((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Mp(e){let t=V.fromRgba(e);return(e,n)=>{let r=V.fromRgba(e);return jp(r,new V(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Np=(e,t)=>t*e[e.length-1][0];function Pp(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function Fp(e,t,n){let r=Np(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Pp(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const Ip=[[.24,1],[.6,0]];function Lp(e,t,n){Dp(e);let r=.9+.2*mp(n,3.1),i=t=>.1*fp(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Mp(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*hp(-.5,.5,fp(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const Rp=e=>Math.abs(e)>=1?0:(1-e*e)**3;function zp(e,t,n,r){Dp(e);let i=e.seconds,a=i/2,o=e=>hp(-.4,.4,fp(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(mp(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*mp(e,8.5+r))),p=i*u/80*(c+l*mp(e,5.5+r)),m=Ap((n-(e+s*mp(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*fp(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((fp(e,t,n)/.8)**2));return{touch:Mp(n),field:(n,i)=>{let[a,o]=Gp(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*Rp((i.col-a-n)/t));let c=i.row+r,l=.8*fp(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function Bp(e,t,n){Dp(e);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*fp(e*1.7+.2,.3+t*2.9,.5+n),l=i+mp(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=mp(u,s+1)<.15?0:1,f=.5+.5*mp(u,s+2),p=mp(u,s+3)*(1-Np(Ip,f)),m=l/r-u-p;return{x:a+c*8+5*(2*mp(u,s+4)-1)+5*f*(2*mp(u,s+5)-1)*Fp(Ip,m,f)+1.5*fp(s,.1,i*.035),y:o+t*3+.6*fp(s,2.2,i*.035),glow:d*Pp(Ip,m,f)}};return{touch:Mp(t),field:(t,n)=>{let r=n.cells(),[s,c]=Gp(r.map(e=>e.col)),[l,u]=Gp(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*Rp(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Vp(e,t){return n=>{let r=V.fromRgba(n.theme.backgroundColor);return au.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-Ap(a(n)));if(i===0)return e;let o=jp(V.fromRgba(e.bg),r,i);return{fg:jp(V.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Hp(e){let t=new Map;return n=>{let r=`${n.row}:${n.col}`,i=t.get(r)??Ap(.5+1.1*pp(n.col*.09+1.4*fp(n.col*.035,n.row*.2+2.6,e+.5),n.row*.45,e,3));return t.set(r,i),i}}function Up(e,t){let n=t=>t>=e.seconds;return{effect:r=>{let i=t(r);return{at:e=>i.at(e),nextChange:e=>n(e)?1/0:i.nextChange(e),lastChange:t=>n(t)?e.seconds:i.lastChange(t)}},done:n}}function Wp(e,t){let n=new Map,r=e=>`${e.row}:${e.col}`;return i=>{let[a,o]=Gp(i.map(t)),s=(o>a?.55:0)*e.seconds,c=iu.once(0,e.seconds-s),l=e=>{let n=o>a?Ap((t(e)-a)/(o-a)):0;return{along:n,progress:e=>c(e-n*s)}};for(let e of i){let t=r(e);n.set(t,n.get(t)??l(e))}return e=>n.get(r(e))??l(e)}}function Gp(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function Kp(e,t){Dp(e);let n=Wp(e,Hp(1.7+t));return Up(e,Vp((t,r)=>{let i=n(r.cells());return n=>e.ease(i(n).progress(t))},e.swing))}const qp={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function Jp(e,t){Dp(e);let n=Hp(9.3+t),r=Wp(e,Hp(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=qp;return Up(e,Vp((t,u)=>{let d=r(u.cells());return r=>{let{along:u,progress:f}=d(r),p=e.ease(f(t)),m=Ap((p-a)/(o-a)),h=i*hp(s,c,n(r))*(1-l+l*u)*Math.sin(Math.PI*m)**2;return 1-p+h}},e.swing))}const Yp=[211,337];function Xp(e,t){Dp(e);let n=e.seconds,r=e=>mp(Number.parseInt(e.slice(1),16)*1e-4,17.3+t),i=(e,n)=>fp(n/Yp[0],5.9+97*e,t)+.5*fp(n/Yp[1],2.3+89*e,t+7.1),a=(t,a)=>{let o=r(t);return 360*a/n+e.swing*180*((i(o,a)-i(o,0))/1.5)},o=new WeakMap;return wp(e=>{let{colors:t,fills:n,depth:r,theme:i}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=o.get(i)??new Go;o.set(i,u);let d=u.get(xp(e),()=>nm(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),f=am(r,i);return au.continuous(e=>{let t=new Map,n=(t,n)=>{let i=Zp(t,a(n,e));return om(i.looks,t,r===z.TRUECOLOR?i.either.map(rm):f,d.get(l(t,n))??$p)},i=(e,r)=>{let i=t.get(l(e,r))??n(e,r);return t.set(l(e,r),i),i};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,t,n,r)=>t?i(e,c(e,n,r)):e;return{fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Zp(e,t){if(t===0)return{looks:e,either:[e]};let n=V.fromRgba(e),r=ws(e),i=e=>new V(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=ws(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Qp=e=>Math.log(Ts(e,new R(0,0,0))),$p={lo:-1/0,hi:1/0},em={lo:1/0,hi:-1/0},tm=Math.log(1.031);function nm(e,t,n){let r=new Map;for(let i of e.filter(e=>_p(e,t)>1)){let e=(Math.log(Ts(i.fg,i.bg))-Math.log(_p(i,t)))/vp.filter(e=>n(i,e)!==void 0).length;for(let t of vp){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Qp(i[t]),Qp(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??$p;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<tm?em:{lo:t,hi:n}]))}const rm=e=>({color:e,looks:V.fromRgba(e),stop:Qp(e)}),im=new WeakMap;function am(e,t){let n=B.indexed(e,t),r=im.get(n)??n.map(([,e])=>rm(e));return im.set(n,r),r}function om(e,t,n,{lo:r,hi:i}){return sm(e,[rm(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function sm(e,t){let n=V.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}const cm={loops:{shimmer:(e,t=Op.shimmer)=>bp(zp(t,24,kp.sun,e.z)),pulse:(e,t=Op.pulse)=>bp(Lp(t,kp.sun,e.z)),sparkle:(e,t=Op.sparkle)=>bp(Bp(t,kp.firefly,e.z)),wheel:(e,t=Op.wheel)=>Xp(t,e.z)},transitions:{fade:(e,t=Op.fade)=>Kp(t,e.z),dissolve:(e,t=Op.dissolve)=>Jp(t,e.z)}};var lm=class{beat;width;_shown;constructor(e){this.beat=ru(e.map(e=>e.seconds));let t=e.map(e=>qf(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}};function um(e,t){return e.at(t).copy().stylize(new H({nextChange:e.nextChange(t)}))}function dm(e,t){let n=[...Hu(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const fm={segments:[],width:0},pm={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function mm(e,t){return pm[e](t)}function hm(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var gm=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}contents(){return this.items}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>dm(Ed(t),e)),o=n=>i?dm(Td(i,null,t[n],{index:n}),e):fm,s=n=>i?dm(Td(i,t[n],null,{index:n+1}),e):fm,c=(n,r)=>i?dm(Td(i,t[n],t[r],{index:r}),e):fm,l=[],u=null,d=r>0?{segments:[new W(` `.repeat(r))],width:r}:fm;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=mm(p,i),o=hm(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new W(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new W(` `.repeat(e)))}yield*t.blocks[e].segments}yield W.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=dm(t[i],e).width,o=this.joiner?dm(Td(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?dm(Td(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=dm(Td(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=dm(Td(this.joiner,null,t[0],{index:0}),e).width,r+=dm(Td(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function _m(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const vm=[`primary`,`secondary`,`accent`],ym=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],bm={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},xm=(e,t)=>`${e}${bm[t]}`,Sm=(e,t,n,r)=>th(e,n,r),Cm=(e,t,n,r)=>rh(e,Gm(e,`text-${t}`),n,r),wm=e=>({tones:[ym[e],ym[e+2],ym[e+1]],text:Sm}),Tm={muted:{tones:[`muted`],text:Cm},deepest:wm(0),deeper:wm(1),middle:wm(2),brighter:wm(3),brightest:wm(4)},Em=1/0,Dm={accent:{hues:[`secondary`,`accent`],run:Em},duo:{hues:[`primary`,`secondary`],run:Em},mono:{hues:[`primary`],run:Em},alt:{hues:[`secondary`,`accent`],run:3}},Om=e=>e.variation.hues.flatMap(t=>e.shade.tones.map(e=>({hue:t,shade:e}))),km=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},Am=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],jm=e=>typeof e==`string`&&Am.includes(e),Mm={"van-der-corput":km,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Nm=e=>Mm[e??`van-der-corput`];function Pm(e){let t=0,n=1;for(let{index:r,count:i,distribution:a}of e)t+=a(r,i)*n,n*=.37;return t%1}const Fm=(e,t)=>Math.floor(e*t),Im=(e,t)=>Math.round(e*t)%t;function Lm(e){return e===void 0?0:e.distribution(e.index,e.count)}function Rm(e,t,n){let r=e[n(Lm(t),e.length)];if(r===void 0)throw Error(`vocabularySelect: empty vocabulary`);return r}function zm(e){let t=e.findIndex(e=>e.axis===`cell`),n=t===-1?e:e.slice(0,t);return{row:n.at(-1),cell:e[n.length]}}const Bm=(e,t)=>Fm(Lm(t),e.hues.length);function Vm(e,t){let{row:n,cell:r}=zm(t);return Hm(e,n,r)}function Hm(e,t,n){let{hues:r,run:i}=e.variation,a=n===void 0?0:Math.floor(n.index/i),o=r[(Bm(e.variation,t)+a)%r.length];if(o===void 0)throw Error(`decorEntryFor: empty variation`);return{hue:o,shade:Rm(e.shade.tones,n,Im)}}function Um(e,t){let{row:n,cell:r}=zm(t),i=r===void 0?[void 0]:Array.from({length:r.count},(e,t)=>({...r,index:t}));return[...new Map(i.map(t=>Hm(e,n,t)).map(e=>[xm(e.hue,e.shade),e])).values()].sort((e,t)=>vm.indexOf(e.hue)-vm.indexOf(t.hue)||Wm.indexOf(e.shade)-Wm.indexOf(t.shade))}const Wm=[...ym,`muted`];function Gm(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}const Km=(e,t)=>Gm(e,xm(t.hue,t.shade)),qm=2.2,Jm=(e,t)=>t.map(t=>Km(e,t)),Ym=e=>t=>Gc(t,e),Xm=Ym(z.TRUECOLOR);function Zm(e,t,n,r){return Qm(e,`${t}|${n.map(e=>e.hex).join(`+`)}|${r}`,()=>$m(e,t,n,r))}const Qm=_m();function $m(e,t,n,r){let i=n.map(Xm),a=Gm(e,t),o=new R(0,0,0),s=new R(255,255,255),c=(e,t)=>V.fromRgba(a).mixAxes(V.fromRgba(e),{l:t,c:0,h:0,alpha:0}).toRgba(),l=e=>Array.from({length:12},(t,n)=>c(e,(n+1)/12)),u=l(o),d=[a,...l(s).flatMap((e,t)=>[e,u[t]])],f=e=>{let t=Ym(e),n=i.map(t);return e=>Math.min(1/0,...n.map(n=>Ts(t(e),n)))},p=f(z.TRUECOLOR),m=f(r),h=e=>Wc(e,r,(e,t)=>i.every(n=>Ts(e,t(n))>=qm)),g=e=>p(e)>=2.2&&h(e)!==void 0,_=(e,t)=>{let n=n=>Ts(Xm(n),e)-Ts(Xm(n),t),r=n(a)<0?o:s,i=r===o?1:-1,[l,u]=[0,1];for(let e=0;e<40;e++){let e=(l+u)/2;i*n(c(r,e))>0?u=e:l=e}return[c(r,l),c(r,u)]},v=()=>{let e=[...i].sort((e,t)=>ws(e)-ws(t));return e.slice(1).flatMap((t,n)=>_(t,e[n]))},y=d.find(g)??[...d,...v()].reduce((e,t)=>m(t)>m(e)?t:e),b=h(y)??y,ee=m(b);return{anchor:y,state:b,short:ee>=2.2?null:ee}}const eh=4.5;function th(e,t,n){return nh(e,`${t.hex}|${n}`,()=>{let r=Hc(t);return rh(e,[`background`,`foreground`].map(t=>Gm(e,t)).reduce((e,t)=>Ts(r,t)<Ts(r,e)?t:e),t,n)})}const nh=_m();function rh(e,t,n,r){return ih(e,`${t.hex}|${n.hex}|${r}`,()=>Uc(t,n,eh,r))}const ih=_m();function ah(e,t,n){return t.depth===0?Jm(e,t.ground):oh(e,t,n)}const oh=(e,t,n)=>t.depth===0?[]:[_h(e,{...t,depth:t.depth-1},n).plane],sh=(e,{short:t},n)=>t===null?[]:[`theme "${e.name}": no open-trigger colour stands ${qm}:1 off every cell beside it — the nearest stands ${t.toFixed(2)}:1 as drawn at depth ${z[n]}; another shade or variation clears it`],ch=(e,t,n)=>t>=fh.triggerPlane?[]:[`theme "${e.name}": an open band's plane stands ΔE ${t.toFixed(3)} off the trigger that opened it as drawn at depth ${z[n]}, under the ${fh.triggerPlane} that tells them apart; another style clears it`],lh={base:.42,perDepth:.14,cap:.75},uh={floor:.12,span:.8};function dh(e,t){return vm[(vm.indexOf(e)+t)%vm.length]}const fh={triggerPlane:.1,nestedPlane:.035};function ph(e,t,n){return mh(e,`${hh(t)}|${n}`,()=>{let r=Zm(e,dh(t.hue,t.depth),ah(e,t,n),n),{state:i}=r,a=xh(e,t,i,n),o=Wc(_h(e,t,n).plane,n,(e,t)=>a.every(n=>n(e,t)));if(o===void 0)throw Error(`palette "${e.name}": the ${t.hue} band at depth ${t.depth} cannot keep its floors on the colours drawn at depth ${z[n]}`);let s=Ym(n);return{state:i,plane:o,shortfalls:n===z.DEFAULT?[]:[...sh(e,r,n),...ch(e,gh(s(i),s(o)),n)]}})}const mh=_m(),hh=({hue:e,depth:t,ground:n})=>`${e}|${t}|${n.map(e=>xm(e.hue,e.shade)).join(`+`)}`,gh=(e,t)=>V.fromRgba(e).deltaE(V.fromRgba(t));function _h(e,t,n){return vh(e,`${hh(t)}|${n}`,()=>yh(e,t,n))}const vh=_m();function yh(e,t,n){let{anchor:r}=Zm(e,dh(t.hue,t.depth),ah(e,t,n),n),i=Math.min(lh.cap,lh.base+lh.perDepth*t.depth),a=(t,n)=>ic(r,Gm(e,t),n),o=oh(e,t,n),s=e=>gh(Xm(r),Xm(e))>=fh.triggerPlane&&o.every(t=>gh(Xm(t),Xm(e))>=fh.nestedPlane),c=a(`background`,i);return{state:r,plane:[c,a(`foreground`,i),a(`background`,lh.cap),a(`foreground`,lh.cap),...bh.toSorted((e,t)=>Math.abs(e-i)-Math.abs(t-i)).flatMap(e=>[a(`background`,e),a(`foreground`,e)])].find(s)??c}}const bh=Array.from({length:12},(e,t)=>(t+1)/12);function xh(e,t,n,r){let{hue:i,depth:a,ground:o}=t,s=t=>_h(e,{hue:i,depth:t,ground:o},r).state,c=t=>_h(e,{hue:i,depth:t,ground:o},r).plane,l=c(a),u=(e,t)=>gh(Xm(l),Xm(t))>=e?e:0,d=Zm(e,dh(i,a+1),ah(e,{hue:i,depth:a+1,ground:o},r),r),f=Ts(Xm(l),Xm(d.anchor))>=2.2?qm:0,p=(e,t)=>(n,r)=>gh(n,r(e))>=t;return[p(n,u(fh.triggerPlane,s(a))),(e,t)=>Ts(e,t(d.state))>=f,...a>0?[p(ph(e,{hue:i,depth:a-1,ground:o},r).plane,u(fh.nestedPlane,c(a-1)))]:[]]}function Sh(e,t,n,r){let i=ph(e,t,r),a=_h(e,t,r),o=e=>ic(a.plane,a.state,e),s=uh.floor+uh.span*Pm(n),c=uh.floor+uh.span/2,l=(e,t)=>e.hex!==t(i.plane).hex&&e.hex!==t(i.state).hex;for(let e=0;e<=12;e++){let t=Wc(o(s+(c-s)*e/12),r,l);if(t!==void 0)return t}return o(s)}const Ch=e=>({kind:`bar`,decor:e,address:[]}),wh=(e,t)=>({...e,address:[...e.address,t]}),Th=e=>({kind:`band`,band:e,address:[]});function Eh(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=Vm(r,i),o=Km(e,a),s;return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{hue:`accent`,depth:0,get ground(){return s??=Um(r,i)}}}}case`band`:{let{band:r,address:i}=t,a=Sh(e,r,i,n);return{tint:a,text:th(e,a,n),disclosure:{...r,depth:r.depth+1}}}}}const Dh=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function Oh(e){let t=typeof e==`string`?Dh.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const kh=`textual-dark`;function Ah(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function jh(){return fl()}function Mh(){return[`bar`,...jh()]}let Nh;function Ph(e){return Nh??=new Set(Mh()),Nh.has(e)}function Fh(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return Ah(e===void 0?null:a(e),t,a(n??r),r,a)}const Ih=[`style`,`palette`,`effect`];function Lh(e){return e!==void 0&&e.includes(`{{`)}function Rh(e,t,n,r,i){let a=Lh(n)?{kind:`expression`,source:n}:i(n??r.name);return Ah(e===void 0?null:i(e),t,a,r,i)}function zh(e,t){return e.kind===`decided`?e:t(e.source)}const Bh=`none`;function Vh(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function Hh(e,t){return Vh(e,t)??Vh(`none`,t)??{kind:`decided`,name:`none`,value:Sc}}function Uh(e,t,n,r){return Rh(e,t,n,Hh(Bh,r),e=>Vh(e,r))}const Wh=`none`,Gh={style:Bh,palette:kh,effect:Wh};function Kh(e,t,n){return`${e} rendered "${Gh[t]}": ${n}`}const qh=Object.freeze([Wh,...Object.keys(cm.loops)]),Jh=Object.freeze([`bar`,...qh]);function Yh(e){let t=qh.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Xh(e){return Yh(e)??{kind:`decided`,name:`none`,value:`none`}}function Zh(e,t,n){return Rh(e,t,n,Xh(Wh),Yh)}const Qh=Object.freeze(Object.keys(Mf)),$h=[`powerline`,`capsule`,`plain`];function eg(e){return $h.includes(e)}const tg=[`truecolor`,`256`,`ansi`,`none`];function ng(e){return Rs(e)??z.DEFAULT}const rg=Object.keys(Dm),ig=Object.keys(Tm),ag=`true`,og=`false`,sg=[ag,og],cg={min:0,max:16};function lg(e){return e===`true`?!0:e===`false`?!1:null}function ug(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const dg=[`vertical`,`horizontal`],fg={vertical:`row`,horizontal:`cell`};function pg(e){return e.id??e.name}function mg(e){return[..._g(e)].flatMap(e=>e.kind===`segment`?[pg(e)]:[])}function hg(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function gg(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*_g(e){yield e;for(let t of xg(e))yield*_g(t)}const vg=(e,t)=>`${e}.children[${t}]`,yg=e=>`${e}.opens.body`;function*bg(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*bg(r,vg(t,n));else e.opens!==void 0&&(yield*bg(e.opens.body,yg(t)))}function xg(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function Sg(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const Cg=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function wg(e){return e.kind===`file`||e.kind===`shell`}const Tg=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Eg=[`fail`,`ignore`];function Dg(e){return e.missingData??`fail`}function*Og(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const kg=`theme`,Ag=`effect`,jg=[kg,Ag];function Mg(e){return{...e.settings,[kg]:{label:kg,domain:`theme`,default:e.palette??`bar`},[Ag]:{label:Ag,domain:Jh,default:`bar`}}}function Ng(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function Pg(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Ng(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Fg(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&Ph(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Ig(e){return String(e)}function Lg(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return ug(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Fg(e,r)?r:void 0}function Rg(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:Lg(n,o))??i}function zg(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Bg=[`left`,`center`,`right`],Vg=[`right`,`left`,`middle`];var Hg=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Kg(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function K(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=Ug(e,n,i);if(t===-1)return r===void 0?void 0:Wg(e,r);n=t,r=t}return r===void 0?void 0:Wg(e,r)}function Ug(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function Wg(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Gg(e,t){try{return _i(t),null}catch(n){if(!(n instanceof di))throw n;return`${e}:${Wg(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Kg(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
|
|
55
|
-
`)}function qg(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${$g(i)}`,line:K(e.source,[...t.split(`.`),r])}),null)}function Jg(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${$g(i)}`,line:K(e.source,[...t.split(`.`),`default`])});return}return i}}function Yg(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${$g(i)}`,line:K(e.source,[...t.split(`.`),r])});return}return i}}function Xg(e,t,n){let r=Yg(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Oh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[...t.split(`.`),`palette`])});return}return r}}function Zg(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${q(a)}`,line:K(e.source,[...t.split(`.`),r])});return}return a}}function Qg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $g(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function q(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function e_(e,t,n,r){return Qg(r)?(i_(e,n,r,t.noun,new Set(Object.keys(t.fields)),t_(e,t.removed??{},n,r)),n_(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${$g(r)}`,line:K(e.source,n.split(`.`))}),null)}function t_(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)a_(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function n_(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const r_=new Set;function i_(e,t,n,r,i,a=r_){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:K(e.source,[...t.split(`.`),o])})}function a_(e,t,n){return e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))}),null}function o_(e,t,n,r){if(!Qg(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${$g(r)}`,line:K(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:K(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:K(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:K(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function s_(e,t,n,r){if(!Qg(r))return e.issues.push({path:n,message:`${n} must be an object, got ${$g(r)}`,line:K(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${$g(i)}`,line:K(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:K(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return i_(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function c_(e,t,n){return{json:S_(b_(n),e,t),keys:new Set([e,...Object.keys(n)])}}function l_(e){return(...t)=>e()(...t)}function u_(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:K(n.source,o.split(`.`))}),null}return a}}function d_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Yg(e,t,r,n)}}function f_(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${$g(i)}`,line:K(e.source,[n])});return}return i}}}}function p_(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${q(o)}`,line:K(e.source,[i])});return}return o}}}}function m_(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${q(a)}`,line:K(e.source,[r])});return}return a}}}}function h_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Xg(e,t,r)}}function g_(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>qg(e,t,r,n)??void 0}}function __(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function v_(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=qg(e,t,r,n);if(i===null)return;let a=__(`${t}.${n}`,i);return a===null?i:a_(e,`${t}.${n}`,a)??void 0}}}function y_(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Zg(t,n,i,r,e)}}function b_(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function x_(e){return b_(e.fields)}function S_(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function C_(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function w_(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const T_={band:{setting:`experimentalBand`,label:`🧪 band (A)`,elsewhere:`the band above the prompt`},statusline:{setting:`experimentalStatusline`,label:`🧪 statusline (B)`,elsewhere:null},pane:{setting:`experimentalPane`,label:`🧪 tmux pane (C)`,elsewhere:`a tmux pane below`},tmuxStatus:{setting:`experimentalTmuxStatus`,label:`🧪 tmux status line (C)`,elsewhere:`the tmux status line`}},E_=Object.keys(T_),D_={by:`request`},O_=e=>`drawing.${e}`,k_={subscribers:0,fps:0,shown:!0},A_=(e,t)=>`feeds.${e}.${t}`;function j_(e){return Object.fromEntries(E_.map(t=>[t,e(t)]))}const M_=j_(()=>k_);function N_(e){return typeof e==`string`&&Object.hasOwn(T_,e)?e:null}const P_=(e,t,n=[])=>({label:e,place:t,previews:n}),F_=(e,t)=>({spec:y_(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e}}}),I_={spec:f_(),domain:`bool`,parse:lg},L_=e=>({spec:p_(e),domain:e,parse:t=>ug(t,e)});function R_(e,t,n,r={}){return{kind:`session`,...F_(e,r.optionDomain),floor:t,control:n,themeDefault:r.themeDefault??!1}}function z_(e,t){return{kind:`session`,...I_,floor:e,control:t,themeDefault:!1}}function B_(e,t,n){return{kind:`session`,...L_(e),floor:t,control:n,themeDefault:!1}}function V_(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const H_=e=>({kind:`text`,spec:e}),U_={required:!1,json:{enum:[...tg]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${tg.join(`, `)}`,line:K(e.source,[...t.split(`.`),n])});return}return Zg(e,t,r,n,tg)}},W_={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Yg(e,t,r,n);return Lh(i)?i:Xg(e,t,r)}},G_={required:!1,json:{anyOf:[{enum:[...qh]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Lh(i)?i:Zg(e,t,r,n,qh)}},K_=/^[^\r\n]*\S[^\r\n]*$/u,q_=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),J_={required:!1,json:{type:`string`,pattern:K_.source,not:{pattern:q_.source}},parse:(e,t,n,r)=>{let i=Yg(e,t,r,n);if(i===void 0||K_.test(i)&&!q_.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:K(e.source,[...t.split(`.`),n])})}},Y_=Object.fromEntries(E_.map(e=>[T_[e].setting,z_(!1,P_(T_[e].label,`toggles`))])),X_={palette:V_(`theme`,W_,{themes:`themes`},P_(`🎨 theme`,`door`)),preset:V_(`preset`,d_(),{from:`presets`},P_(`▦`,`door`,[`layout`,`presetDelete`])),style:V_(`style`,d_(),{from:`styles`},P_(`◐`,`gear`,[`palette`]),{themeDefault:!0}),effect:V_(`effect`,G_,{from:qh},P_(`✨`,`look`)),endcaps:R_(Qh,`powerline`,P_(`✦`,`look`),{optionDomain:`endcaps`}),variation:R_(rg,`accent`,P_(`🎼`,`gear`,[`layout`]),{optionDomain:`variations`,themeDefault:!0}),shade:R_(ig,`middle`,P_(`🔆`,`gear`,[`layout`]),{optionDomain:`shades`,themeDefault:!0}),transitions:z_(!1,P_(`fade in/out`,`look`)),autoWrap:z_(!0,P_(`wrap`,`config`)),padding:B_({...cg,step:1},1,P_(`padding`,`config`)),updateNotice:z_(!0,P_(`update notice`,`config`)),...Y_,colorCompatibility:{kind:`config`,...F_(tg,`colorCompatibilities`),spec:U_,floor:`truecolor`},default_empty_value:H_(d_()),default_separator:H_(d_()),menuGlyph:H_(J_)},Z_=Object.entries(X_),Q_=Z_.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),$_=Z_.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),ev=Z_.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),tv=Z_.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function nv(e){return X_[e]}const rv=e=>nv(e).floor;function iv(e){let t=X_[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const av=e=>`${e}.effective`,ov=e=>{let t=X_[e];return t.kind===`selection`?t.sessionKey:e},sv=Object.fromEntries($_.map(e=>{let t=ov(e);return[t,{configKey:e,sessionKey:t,effectiveVar:av(t),...X_[e].control}]})),cv=Object.keys(sv),lv=Object.values(sv),uv=Q_.filter(e=>X_[e].kind===`config`).map(e=>({configKey:e,effectiveVar:av(e)})),dv=new Set(uv.map(e=>e.configKey)),fv=new Map([...lv,...uv].map(e=>[e.configKey,e.effectiveVar])),pv=new Map(lv.map(e=>[e.sessionKey,e.effectiveVar]));function mv(e){return Object.fromEntries(cv.map(t=>[t,e(t)]))}const hv=new Map(cv.map(e=>[sv[e].sessionKey,e])),gv=[[0,31],[127,159],[8234,8238],[8294,8303]];function _v(e){return gv.some(([t,n])=>e>=t&&e<=n)}function vv(e){let t=``;for(let n of e)t+=_v(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function yv(e,t){let n=vv(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const bv=`\x1B[38;2;255;255;255m`,xv=`\x1B[48;2;200;40;40m`,Sv=`\x1B[0m`;function Cv(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const wv={fg:Cv(bv),bg:Cv(xv)},Tv={fg:Cv(`\x1B[38;2;0;0;0m`),bg:Cv(`\x1B[48;2;220;160;40m`)},Ev=new Cu({"strip.separator":`default`,"strip.rail":`default`});function Dv(e){return Ev.resolve(e)}const Ov={kind:`still`},kv=Symbol(`bar`);function Av(e){return e.name!==Wh}function jv(e,t){return n=>au.map(au.all(t.map(({t,effect:r})=>pu.run(pu.play(e-t),r(n)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const Mv=xl;function Nv(e,t){let n=new ac(t,Mv.foregroundColor,Mv.ansiColors,Mv.palette);return t=>e({...t,theme:n})}function Pv(e,t){return n=>ep(()=>e(n),...t)(n)}function Fv(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const Iv=4096;var Lv=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Wh,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(({passage:e})=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:kv,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision&&u.source.width===n.source.width?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h=[],g={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m,leaves:h},_=(e,n,{ground:r})=>{let i=cm.transitions[e]({z:Fv(`${this.key}@${n}`)*Iv});return{name:e,since:t,transition:{effect:Nv(i.effect,r),done:e=>i.done(e)}}},v=({since:e,transition:n})=>n.done(t-e),y=(e,t,n)=>({drawing:t,passage:f===null?null:n===void 0||n.passage?.name===`dissolve`?_(`fade`,e,t):n.passage!==null&&!v(n.passage)?n.passage:null}),b=(e,t)=>{if(t===void 0||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return v(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:_(`dissolve`,e,r)}},ee=(e,r)=>{if(p.has(e))throw Error(`placement "${e}" was reached twice in one frame`);let i=f?.get(e),{drawing:a,deeper:o}=n.returned(e,r),s=a===null?b(e,i):y(e,a,i);return s===void 0?r:(p.set(e,s),s.passage!==null&&(s.passage.name===`fade`?m:h).push({placement:e,t:t-s.passage.since}),a===null?[...s.drawing.own,...o]:r)},x=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},S=(e,t)=>{let n=c.get(e)??new Map;c.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=s.get(e)?.get(t.scope),a=i?.name===t.name,o=Fv(t.scope===kv?e:`${e}@${t.scope}`),l=a?i.effect:cm.loops[t.name]({z:o*Iv});return g[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:l}),l},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:x(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},ne=e=>{let n=new Map;for(let{owner:t,placement:r}of e){let e=n.get(r.id);e===void 0?n.set(r.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=p.get(e)?.passage??null;return r===null?[]:[{t:t-r.since,effect:ep(r.transition.effect,...n)}]})};return{placed:d===`off`?(e,t)=>t:ee,row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?te(t):[{...i,owners:void 0}]).filter(Av),r=ne(t);if(n.length===0&&r.length===0)return Ov;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:e=>new Jf(e,jv(i.t,[...n.map(e=>{let t=S(a,e);return{t:e.t,effect:e.owners===void 0?t:Pv(t,e.owners)}}),...r]),{t:i.t,key:a,theme:Mv})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=g}}}},Rv=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new Lv(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function zv(e,t){let n=Ls(t.colorSystem),r=[...Hu(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:Ev,colorSystem:n.colorSystem,onStyleError:e=>{throw e}})];return{text:Pf(r,n),moves:Number.isFinite(W.nextChange(r))}}const Bv=new Map;function Vv(e){let t=Bv.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>`cap`in t?t:{...t,glyph:e});return{seam:n,divider:n}},{seam:r,caps:i}=Mf.plain,a=new ef({glyph:n(r.glyph),ascii:r.ascii},i);return Bv.set(e,a),a}function Hv(e,t){return e===`plain`&&t!==void 0?Vv(t):Mf[e]}const Uv=new Map;function Wv(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=Uv.get(t);if(n!==void 0)return n;let r=Hv(e.endcaps,e.separator),i=e=>new G(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=e=>new G(zv(new Dd(e,r),{colorSystem:null}).text.replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return Uv.set(t,s),s}function Gv(e){return Wv(e).chrome}function Kv(e){return Wv(e).seam}const qv=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function Jv(e){return[...new Set(e.match(qv)??[])].join(``)}function Yv(e){let t=Hv(e.endcaps,e.separator),n=e=>new G(`x`,{end:``,style:new H({bgcolor:e})});return Jv(zv(new Dd([n(`#101010`),n(`#202020`),n(`#202020`)],t),{colorSystem:null}).text)}function Xv(e,t,n=Ov){if(e.length===0)return{text:``,moves:!1};let r=Hv(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new gm([...e],{joiner:r}):new Dd([...e],r),s=zv(n.kind===`still`?o:n.wrap(o),a);if(!s.text.endsWith(`
|
|
56
|
-
`))throw Error(`drawStripCells: rich-js strip output did not end its last line`);return{text:s.text.slice(0,-1),moves:s.moves}}function
|
|
57
|
-
`)}function
|
|
58
|
-
`);return e?`${l}\n${e}`:l}function
|
|
59
|
-
`)}function
|
|
60
|
-
`))}function fy(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:o,failedConfigFile:s}=t,c=new H({bgcolor:i.bg,color:i.fg}),l=(e,t)=>new G(e,{style:t,end:``,overflow:`ignore`}),u=n>0?[l(`${n} more rows · `,c),o.kind===`file`?l(`open full text`,c.withLink(a(o.path).href)):l(`full text unavailable: ${vv(o.reason)}`,c)]:[],d=s===null?[]:[l(`${u.length>0?` · `:``}open `,c),l(vv(s),c.withLink(a(s).href))],f=[l(`↳ `,c),...u,...d.slice(0,-1)],p=f.reduce((e,t)=>e+t.cellLength,0),m=d.slice(-1).map(e=>e.truncate(Math.max(1,r.width-p),{mode:`middle`})),h=G.fromFragments([...f,...m]).truncate(r.width);return h.overflow=`ignore`,Zv([h],r)}var J=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const py=new Map;function my(e){let t=gy(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function hy(e,t){return e===`bar`?t:my(e)}function gy(e){let t=py.get(e);if(t!==void 0)return t;let n=pl(e);return n===null?null:(py.set(e,n),n)}function _y(e,t){return vy(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Tl(e,t))}const vy=_m();function yy(e){let t=gy(e);return t===null?null:{kind:`decided`,name:e,value:t}}function by(e,t,n){let r=yy(e);return r===null?(n(Kh(t,`palette`,`"${e}" names no installed theme${Oh(e)}`)),Sy()):r}function xy(e,t,n){return Rh(e,t,n,Sy(),yy)}function Sy(){return{kind:`decided`,name:kh,value:my(kh)}}const Cy=/^[A-Za-z_][A-Za-z0-9_]*$/;function wy(e){return`#${e+1}`}const Ty={rows:{}};function Ey(e){return`rows`in e}function Dy(e){return Object.fromEntries(e.map((e,t)=>[wy(t),e]))}function Oy(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Dy(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Dy([n])}}function ky(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Ay(e){return Ey(e)?ky(e):e}function*jy(e,t){if(!Ey(e)){yield*bg(e,t);return}yield[ky(e),t];for(let[n,r]of Object.entries(e.rows))yield*bg(r,`${t}.rows.${n}`)}function My(e,t){return Ey(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Oy(e)}function Ny(e){if(!Ey(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Py=`default`,Fy={};function Iy(e){return[...new Set([Py,...Object.keys(e)])]}function Ly(e,t,n){return Fh(void 0,e,t,Py,n)}function Ry(e,t){let n={[Py]:Fy,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Py}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function zy(e,t){let n=Ry(e.presets,t).root??Ty;return{node:ky(My(n,e.root)),path:Ny(n)?`presets.${t}.root`:`root`}}function By(e,t){return{...e.globals,...Ry(e.presets,t).globals}}const Vy=new Map;function Hy(e,t,n){Vy.set(e,{permanent:!0,resolve:t,paletteOf:n})}Hy(`themes`,()=>jh(),e=>my(e));const Uy=`placementThemes`;Hy(Uy,Mh,(e,t)=>hy(e,t.palette));for(let{name:e,members:t}of tv)Hy(e,()=>t);function Wy(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>_y(n.basePalette,e.styles[t])}],[`presets`,{members:Iy(e.presets)}]])}function Gy(e){return[...new Set([...Vy.keys(),...e.keys()])]}function Ky(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=Vy.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(Jy(e,t))}const qy=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function Jy(e,t){let n=qy.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Gy(t).join(`, `)})`}const Yy=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*Xy(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const Zy=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,Qy=RegExp(`^(?:(\\$)(?:\\.(${Zy}))?|\\.(${Zy})?)(?=[\\s)]|$)`);function $y(e,t,n){let r=Qy.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const eb=/^(\w+)\b\s*([\s\S]*)$/;function*tb(e,t){let n=[t];for(let r of Xy(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=eb.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:$y(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push($y(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const nb=/(?<![.$])\btemplate\s+$/;function*rb(e,t,n){let r=0;for(let i of[...e.matchAll(Yy)]){let a=i.index+i[0].length;nb.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:$y(e.slice(a),t,n)}),r=a}}function*ib(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...tb(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...rb(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const ab=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${Zy})`,`g`);function*ob({code:e,dot:t,root:n}){let r=e.replace(Yy,``);for(let e of[...r.matchAll(ab)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function sb(e,t){let n=new Map;for(let r of ib(e,t))for(let e of ob(r))n.has(e)||n.set(e,r.via);return n}const cb=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,lb={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*ub(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(Yy)]){let o=e.slice(t,a.index),s=cb.exec(o);if(s!==null)n=lb[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function db(e,t){let n=new Map;for(let{code:r,via:i}of ib(e,t))for(let{name:e,site:t}of ub(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function fb(e,t){return new Set([...pb(e,t)].filter(e=>Object.hasOwn(t,e)))}function pb(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of ib(e,t))for(let{name:e}of rb(r,i,a))n.add(e);return n}function mb(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function hb(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),gb(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function gb(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&Sg(e.parse)===`json`}function _b(e){let t=s.basename(e),n=s.dirname(e);for(;;){let r=vb(n);if(r!==null)return{dir:r,name:t,leaf:n===s.dirname(e)};t=s.basename(n),n=s.dirname(n)}}function vb(e){try{return p.statSync(e).isDirectory()?p.realpathSync(e):null}catch{return null}}var yb=Te((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Vt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Lt(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Rt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Ht,n=Ht){let r=new Gt(e);return t!==Ht&&(r.onBOL=new Set([t])),n!==Ht&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||tt(e)?e:Array.isArray(e)?cn.array(e,{name:n}):o(e)?cn.object(e,void 0,{name:n}):u(e)?cn.map(e,{name:n}):d(e)?cn.set(e,{name:n}):typeof e!=`function`||We(e)||Qe(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:ee,u:x}}function ee(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:We(n.value)?1:(Lt(r,t,te(e,this,t,n,!1)),2)}function x(e,t,n,r){let i=te(e,this,t,n);return e.l(t,i,r)}function S(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return ye(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return We(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(We(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function te(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:ye(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function ne(e,t){return{t:e,i:t,o:C,u:re}}function C(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!Qe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Qe(n.value)?1:(Lt(r,t,ae(e,0,0,n,!1,!1)),2)}function re(e,t,n,r){let i=ae(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ie(e,t,n){var r;let{name:i,addInitializer:a}=n;return Qe(t)||(t=Gn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function ae(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Qe(o)||(o=Gn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function w(e,t){return{t:e,i:t,o:T,u:oe}}function T(e,t,n){return this.u(e,t,n,!1)===null?0:1}function oe(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function E(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new M(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[A],n=this,i=e.j.get(a);i instanceof M&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[A],n=e.j.get(a);if(n instanceof M&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function se(e,t){return{t:e,i:t,o:ce,u:le}}function ce(e,t,n){return this.u(e,t,n,!1)===null?0:1}function le(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ue(e,t,n){function r(e,t){let n=Ct(e)[A];return(n.V??=new Map).set(o,()=>new vn(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[A]??r(this,t.get.call(this)))._(o)},set(e){return(this[A]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function de(e){return{t:Yt,i:e,o:fe,u:pe}}function fe(e,t,n,r){var i,a,o;if(n.get)return fn.o(e,t,n,r);if(n.set){let i=We(n.set)?n.set:ye(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(Lt(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?rn:cn;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function pe(e,t,n,r){var i;return n.get?fn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:ye(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?rn:cn).u(e,t,n,r))}function me(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function he(e){return e||Zt}function ge(e){return me(e,ue)}function _e(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function ve(e){return me(e,E)}function ye(e,t,n=!1,r){function i(){return be(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),gn&&(_n.value=e,Lt(i,`name`,_n)),i}function be(e,t,n,r,i){let a=xe(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{Se(a)}}function xe(e,t){let n=N.trackingDerivation,r=!t||!n;Pe();let i=N.allowStateChanges;r&&Oe();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:hn++,D:mn};return mn=a.B,a}function Se(e){mn!==e.B&&t(30),mn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Fe(),e.R&&ke(e.k),N.suppressReactionErrors=!1}function Ce(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function we(e){return e instanceof xn}function Te(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Oe(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return ke(t),!0}if(e.K===2)return ke(t),!0}}return Ae(e),ke(t),!1}}}function Ee(e,t,n){Ae(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&Me(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,je(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function De(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Me(t[n],e);e.K=-1}function D(e){let t=Oe();try{return e()}finally{ke(t)}}function Oe(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function ke(e){N.trackingDerivation=e}function Ae(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function je(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Me(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ne(e))}function Ne(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function Pe(){N.inBatch++}function Fe(){--N.inBatch===0&&(ze(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof M&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ie(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ie))}function Le(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ne(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Re(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function ze(){N.inBatch>0||N.isRunningReactions||On(Be)}function Be(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Ve(e){return me(e,S)}function He(e){return function(t,n){return n&&typeof n.kind==`string`?S(e?Pn:Mn,t,n):r(t)?ye(t.name||`<unnamed action>`,t,e):r(n)?ye(t,n,e):i(t)?Ve(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Ue(e){return be(0,!1,e,this,void 0)}function We(e){return r(e)&&!0===e.isMobxAction}function Ge(e,t=Bt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ke(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function Ke(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function qe(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Je(e,t,n,r){let i=Wt(t);return kt(()=>{let t=Ct(e,r)[A];Ut(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ye(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Ye)),t}function Xe(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),Xe)),t}function Ze(e){r(e.cancel)&&e.cancel()}function Qe(e){return!0===e?.isMobXFlow}function $e(e,t){var n;if(t===void 0)return bn(e);if(!1===Tt(e))return!1;let r=e[A];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Et(e,t)):!1}function et(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[A];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[A]||Kt(e)||kn(e)||bn(e)}function tt(e){return et(e)}function nt(e){return Tt(e)?e[A].nt():ir(e)||sr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function rt(e,n){return Tt(e)?e[A].et(n):ir(e)||sr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function it(e){if(Tt(e))return e[A].it();t(38)}function at(e,t,n){if(bn(e)){let r,i=!0;return Ge(()=>{let a=e.get();if(!i||n){let n=Oe();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),ke(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),mt(e,t)}function ot(e,t,n){return e.set(t,n),n}function st(e,t){if(typeof e!=`object`||!e||e instanceof Date||!tt(e))return e;if(yn(e)||bn(e))return st(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=ot(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=st(e,t)}),n}if(sr(e)){let n=ot(t,e,new Set);return e.forEach(e=>{n.add(st(e,t))}),n}if(ir(e)){let n=ot(t,e,new Map);return e.forEach((e,r)=>{n.set(r,st(e,t))}),n}{let n=ot(t,e,{});return it(e).forEach(r=>{Rt.propertyIsEnumerable.call(e,r)&&(n[r]=st(e[r],t))}),n}}function ct(e,t){Pe();try{return e.apply(t)}finally{Fe()}}function lt(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[A].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=ye(`When-effect`,t);var a=Ge(t=>{Ce(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ut(e){return e[A]}function dt(e){return e.st!==void 0&&e.st.length>0}function ft(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function O(e,n){let r=Oe();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{ke(r)}}function pt(e){return e.ot!==void 0&&e.ot.length>0}function mt(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function ht(e,t){let n=Oe(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);ke(n)}}function gt(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==Rt;){let t=It(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function k(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function _t(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[A];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function bt(e){return a(e)&&er(e[A])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,A))return e;let n=t?.name??`ObservableObject`;return c(e,A,new ur(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return j[r]??(j[r]=de({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return cr[e]||(cr[e]={get(){return this[A]._(e)},set(t){return this[A].M(e,t)}})}function Tt(e){return!!a(e)&&dr(e[A])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[A].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[A],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Kt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[A]))return e[A];t(28)}function Dt(e,n){return e||t(29),n===void 0?Kt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[A]?e[A]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(We(e))return e.name;n=Tt(e)||ir(e)||sr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=Oe();Pe();try{return e()}finally{Fe(),ke(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=fr.call(e);if(s!==fr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=Mt(e),t=Mt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!jt(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(pr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,It=Object.getOwnPropertyDescriptor,Lt=Object.defineProperty,Rt=Object.prototype,zt=[];Object.freeze(zt);let Bt={};Object.freeze(Bt);let Vt=Object.toString(),Ht=()=>{},Ut=Reflect.ownKeys,Wt=Object.getOwnPropertyDescriptors,A=Symbol(`mobx administration`);var Gt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Le(this)}reportChanged(){Pe(),Re(this),Fe()}toString(){return this.tt}};let Kt=l(`Atom`,Gt),qt=Object.is,Jt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Yt=`true`,Xt=de(),j=[Xt],Zt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Zt);let Qt=se(`observable`),$t=se(`observable.ref`,{A:y}),en=se(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ir(e)||sr(e)?e:Array.isArray(e)?cn.array(e,{name:n,deep:!1}):o(e)?cn.object(e,void 0,{name:n,deep:!1}):u(e)?cn.map(e,{name:n,deep:!1}):d(e)?cn.set(e,{name:n,deep:!1}):void 0}}),tn=se(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),nn={box(e,t){let n=he(t);return new vn(e,_e(n),n.name,!0,n.equals)},array(e,t){let n=he(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new Qn(n,t,r);Lt(i.j,A,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,_e(n),n.name)},map(e,t){let n=he(t);return new rr(e,_e(n),n.name)},set(e,t){let n=he(t);return new or(e,_e(n),n.name)},object:(e,t,n)=>kt(()=>Je(function(e,t){var n;return(n=(e=Ct(e,t))[A]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},rn=ge($t),an=ge(en),on=ge(Qt),sn=ge(tn);var cn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ue(Qt,e,t):tt(e)?e:o(e)?cn.object(e,t,n):Array.isArray(e)?cn.array(e,t):u(e)?cn.map(e,t):d(e)?cn.set(e,t):typeof e==`object`&&e?e:cn.box(e,t)},Qt,nn);let ln=`computed`,un=w(ln),dn=ve(w(`computed.struct`,{equals:_})),fn=function(e,t){if(t&&typeof t.kind==`string`)return E(un,e,t);if(o(e))return ve(w(ln,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new M(n)};var pn;Ft(fn,un);let mn=0,hn=1,gn=(pn=It(()=>{},`name`)?.configurable)!=null&&pn,_n={value:`action`,configurable:!0,writable:!1,enumerable:!1};var vn=class extends Gt{constructor(e,t,n=`ObservableValue`,r=!0,i=qt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(dt(this)){let t=O(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),pt(this)&&ht(this,{type:Xn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let yn=l(`ObservableValue`,vn);var M=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new xn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=ye(`ComputedValue-setter`,e.set)),this.xt=e.equals||qt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Le(this),Te(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ie)}else Te(this)&&(this.Nt(),Pe(),this.rt=this.Rt(!1),Fe());let e=this.rt;if(we(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||we(e)||we(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Ee(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(De(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,M);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),ze())}X(){if(!this.isDisposed){Pe(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,Te(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Fe()}}track(e){if(this.isDisposed)return;Pe(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Ee(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&De(this),we(n)&&this.Pt(n.cause),Fe()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Pe(),De(this),Fe()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=He(!1);Ft(In,Mn);let Ln=He(!0);Ft(Ln,Pn);let Rn=Ve(Nn),zn=Ve(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=ne(`flow`),Wn=ne(`flow.bound`,{bound:!0}),Gn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return ie(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=In(i,function(){try{o&&Ze(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ht,Ht),Ze(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=me(Wn,ie),qn={has:(e,t)=>ut(e).et(t),get:(e,t)=>ut(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ut(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ut(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ut(e).l(t,n))==null||r},ownKeys:e=>ut(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[A];return t===A?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[A];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Gt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=zt),dt(this)){let r=O(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return zt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&ht(this,i)}Ft(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&ht(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(dt(this)){let n=O(this,{type:Xn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[A];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[A].wt(e,t,n)},push(...e){let t=this[A];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[A].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};k(`at`,_t),k(`concat`,_t),k(`flat`,_t),k(`includes`,_t),k(`indexOf`,_t),k(`join`,_t),k(`lastIndexOf`,_t),k(`slice`,_t),k(`toString`,_t),k(`toLocaleString`,_t),k(`toSorted`,_t),k(`toSpliced`,_t),k(`with`,_t),k(`every`,vt),k(`filter`,vt),k(`find`,vt),k(`findIndex`,vt),k(`findLast`,vt),k(`findLastIndex`,vt),k(`flatMap`,vt),k(`forEach`,vt),k(`map`,vt),k(`some`,vt),k(`toReversed`,vt),k(`reduce`,yt),k(`reduceRight`,yt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[A]=tr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,kt(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new vn(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(dt(this)){let r=O(this,{type:n?Xn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=pt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ct(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}}Jt(e,t){ct(()=>{var n;let r=new vn(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=pt(this);n&&ht(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return xt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return xt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ir(e)&&(e=new Map(e)),ct(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Rt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){ct(()=>{D(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ct(()=>{let n=function(e){if(u(e)||ir(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[A]=ar,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ct(()=>{D(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(dt(this)){let t=O(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ct(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=pt(this);t&&ht(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=pt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return ct(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return St({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ct(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Xt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Gt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof M)return n.set(t),!0;if(dt(this)){let n=O(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}return!0}Tt(e){return N.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new vn(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Lt(this.h,e,t);this.Yt(e,t.value)}finally{Fe()}return!0}S(e,t,n,r=!1){try{Pe();let i=this.Dt(e);if(!i)return i;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Lt(this.h,e,o);let s=new vn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Fe()}return!0}m(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=wt(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Lt(this.h,e,a);this.j.set(e,new M(t)),this.Yt(e,void 0)}finally{Fe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;Pe();let r=pt(this),i=this.j.get(e),a;if(i||!r||(a=It(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof vn&&(a=i.rt),Re(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&ht(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Fe()}return!0}Yt(e,t){var n;let r=pt(this);r&&r&&ht(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Ut(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Rt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=A,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=Ce,e._allowStateChangesInsideComputed=Ue,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=Se,e._getAdministration=Dt,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||bt(e)||yn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=xe,e.action=In,e.actionBound=Rn,e.autorun=Ge,e.compareDefault=qt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=fn,e.computedStruct=dn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[A].l(n,r);t(39)},e.entries=function(e){return Tt(e)?nt(e).map(t=>[t,e[t]]):ir(e)?nt(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Je,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(rt(e,n))return Tt(e)?e[A].Tt(n):ir(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return Ye(Et(e,t))},e.getObserverTree=function(e,t){return Xe(Et(e,t))},e.has=rt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ft(Dt(e,t),n)}(e,t,n):function(e,t){return ft(Dt(e),t)}(e,t)},e.isAction=We,e.isBoxedObservable=yn,e.isComputed=function(e){return $e(e)},e.isComputedProp=function(e,t){return $e(e,t)},e.isFlow=Qe,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=tt,e.isObservableArray=bt,e.isObservableMap=ir,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return et(e,t)},e.isObservableSet=sr,e.keys=nt,e.makeAutoObservable=function(e,t,n){return o(e)?Je(e,e,t,n):(kt(()=>{let r=Ct(e,n)[A];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ut(e),...Ut(t)]);n.delete(`constructor`),n.delete(A),c(t,Jn,n)}e[Jn].forEach(e=>gt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[A];Ut(t).forEach(e=>gt(r,e,t[e]))}),e},e.observable=cn,e.observableDeep=on,e.observableRef=rn,e.observableShallow=an,e.observableStruct=sn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return at(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ir(e)&&!sr(e)&&!Tt(e))return at(r,t,n);return mt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return qe(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return qe(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=Jt,e.ownKeys=it,e.reaction=function(e,t,n=Bt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=Ce(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=In(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=Ke(n),d,f=!0,p=!1,m=n.equals||qt,h=new En(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Tt(e)?e[A].Dt(n):ir(e)||sr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ue,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){Pe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Fe()}return}Tt(n)?n[A].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Pe(),r>=n.length&&(n.length=r+1),n[r]=i,Fe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return st(e,new Map)},e.transaction=ct,e.untracked=D,e.values=function(e){return Tt(e)?nt(e).map(t=>e[t]):ir(e)?nt(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):bt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=lt(e,n,Ft({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):lt(e,t,n||{})}})),bb=Te((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++j.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=ie(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function ee(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function x(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function S(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function te(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let ne=Reflect.ownKeys;function C(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function re(e){return e===null?null:typeof e==`object`?``+e:e}function ie(e,t){return o.hasOwnProperty.call(e,t)}let ae=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function T(e,t,n){return n?e|=t:e&=~t,e}function oe(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let E=Symbol(`mobx administration`);var se=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return w(this.flags_,1)}set isBeingObserved(e){this.flags_=T(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=T(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=T(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return un(this)}reportChanged(){on(),dn(this),sn()}toString(){return this.name_}};let ce=b(`Atom`,se);function le(e,t=f,n=f){let r=new se(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ue(e,t){return e===t}function de(e,t){return Li(e,t)}function fe(e,t){return Li(e,t,1)}let pe=Object.is;function me(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?O.array(e,{name:n}):g(e)?O.object(e,void 0,{name:n}):ee(e)?O.map(e,{name:n}):S(e)?O.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function he(e,t,r){if(e==null||ki(e)||fi(e)||gi(e)||xi(e))return e;if(Array.isArray(e))return O.array(e,{name:r,deep:!1});if(g(e))return O.object(e,void 0,{name:r,deep:!1});if(ee(e))return O.map(e,{name:r,deep:!1});if(S(e))return O.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function ge(e){return e}function _e(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ve=`override`,ye={annotationType_:ve,make_:xe,extend_:Se};function be(e){return e.annotationType_===ve}function xe(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ie(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function Se(e,t,r,i){n(44,this.annotationType_)}function Ce(e,t){return{annotationType_:e,options_:t,make_:we,extend_:Te}}function we(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:zn(n.value)?1:(a(r,t,D(e,this,t,n,!1)),2)}function Te(e,t,n,r){let i=D(e,this,t,n);return e.defineProperty_(t,i,r)}function Ee(e,t,r){oe(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function De(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function D(e,t,n,r,i=j.safeDescriptors){var a,o;De(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Oe(e,t){return{annotationType_:e,options_:t,make_:ke,extend_:Ae}}function ke(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!ie(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ne(e,this,t,n,!1,!1)),2)}function Ae(e,t,n,r){let i=Ne(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function je(e,t,n){var r;oe(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function Me(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Ne(e,t,n,r,i,a=j.safeDescriptors){Me(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Pe(e,t){return{annotationType_:e,options_:t,make_:Fe,extend_:Ie}}function Fe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ie(e,t,n,i){return Re(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Le(e,t,n){oe(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new At(o)}return o(function(){let e=Ei(this)[E],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[E],n=e.values_.get(a);if(n instanceof At&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function Re(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function ze(e,t){return{annotationType_:e,options_:t,make_:Be,extend_:Ve}}function Be(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ve(e,t,n,r){return Ue(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??me,r)}function He(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);oe(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Ei(e)[E];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??me,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[E]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[E]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ue(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let We=Ge();function Ge(e){return{annotationType_:`true`,options_:e,make_:Je,extend_:Ye}}let Ke=[We];function qe(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ke[r]??(Ke[r]=Ge({deep:t,autoBind:n}))}function Je(e,t,n,r){var i;if(n.get)return k.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?lt:O;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ye(e,t,n,r){var i;return n.get?k.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:xt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?lt:O).extend_(e,t,n,r))}function Xe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Ze={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ze);function Qe(e){return e||Ze}let $e=ze(`observable`),et=ze(`observable.ref`,{enhancer_:ge}),tt=ze(`observable.shallow`,{enhancer_:he}),nt=ze(`observable.struct`,{enhancer_:_e});function rt(e){return Xe(e,He)}function it(e){return e.deep===!0?me:e.deep===!1?ge:ot(e.defaultDecorator)}function at(e){return e?e.defaultDecorator??qe(e):void 0}function ot(e){return e?e.options_?.enhancer_??me:me}function st(e,t,n){return t&&typeof t.kind==`string`?He($e,e,t):xr(e)?e:g(e)?O.object(e,t,n):Array.isArray(e)?O.array(e,t):ee(e)?O.map(e,t):S(e)?O.set(e,t):typeof e==`object`&&e?e:O.box(e,t)}let ct={box(e,t){let n=Qe(t);return new Ot(e,it(n),n.name,!0,n.equals)},array(e,t){let n=Qe(t);return ai(e,it(n),n.name)},map(e,t){let n=Qe(t);return new hi(e,it(n),n.name)},set(e,t){let n=Qe(t);return new bi(e,it(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},lt=rt(et),ut=rt(tt),dt=rt($e),ft=rt(nt);var O=r(st,$e,ct);let pt=`computed`;function mt(e){return Xe(e,Le)}let ht=Pe(pt),gt=mt(Pe(`computed.struct`,{equals:de})),k=function(e,t){if(t&&typeof t.kind==`string`)return Le(ht,e,t);if(g(e))return mt(Pe(pt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new At(r)};r(k,ht);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=j.trackingDerivation,c=!t||!o;on();let l=j.allowStateChanges;c&&(Ut(),l=Et(!0));let u=j.allowStateReads;A(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(j.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Gt(e.prevAllowStateReads_),sn(),e.runAsAction_&&Wt(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),j.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}function Dt(e){j.allowStateChanges=e}var Ot=class extends se{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=pe){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&bn()&&xn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==j.UNCHANGED){let n=bn();n&&Sn({type:ni,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(It(this),Kr(this)){let t=P(this,{object:this,type:ni,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?j.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Jr(this)&&Xr(this,{type:ni,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new Mt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||pe,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){pn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return w(this.flags_,1)}set isComputing(e){this.flags_=T(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=T(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=T(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),j.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),on(),this.value_=this.computeValue_(!1),sn());else{let e=this.isBeingObserved;if(un(this),Pt(this)){let e=j.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(j.trackingContext=this),this.trackAndCompute()&&fn(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(ln)}let e=this.value_;if(Nt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Rt(this,this.derivation,this.scope_);else if(j.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Vt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:j.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=A(!0),n=Ut(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(j.disableErrorBoundaries)i.get();else try{i.get()}catch{return Wt(n),Gt(t),!0}if(e.dependenciesState_===2)return Wt(n),Gt(t),!0}}return Kt(e),Wt(n),Gt(t),!1}}}function Ft(){return j.trackingDerivation!==null}function It(e){let t=!!e.observers_&&e.observers_.size>0;!j.allowStateChanges&&(t||j.enforceActions===`always`)&&console.warn(`[MobX] `+(j.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function Lt(e){!j.allowStateReads&&j.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Rt(e,t,n){let r=A(!0);Kt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++j.runId;let i=j.trackingDerivation;j.trackingDerivation=e,j.inBatch++;let a;if(j.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return j.inBatch--,j.trackingDerivation=i,Bt(e),zt(e),Gt(r),a}function zt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:j.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Bt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&rn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,nn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Vt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)rn(t[n],e);e.dependenciesState_=-1}function Ht(e){let t=Ut();try{return e()}finally{Wt(t)}}function Ut(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function Wt(e){j.trackingDerivation=e}function A(e){let t=j.allowStateReads;return j.allowStateReads=e,t}function Gt(e){j.allowStateReads=e}function Kt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let qt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Jt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Yt=!0,Xt=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Yt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Yt=!1),Yt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Jt):(setTimeout(()=>{Xt||n(35)},1),new Jt)}();function Zt(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&n(36),Xt=!0,Yt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Jt}}function Qt(){return j}function $t(){let e=new Jt;for(let t in e)qt.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions}function en(e){return!!e.observers_&&e.observers_.size>0}function tn(e){return e.observers_??new Set}function nn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&an(e))}function an(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function on(){j.inBatch++}function sn(){--j.inBatch===0&&(_n(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&cn())}function cn(){j.isRunningUnobservations=!0;try{let e=j.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof At&&n.suspend_())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}function ln(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(ln))}function un(e){Lt(e);let t=j.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&j.inBatch>0&&an(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function dn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function fn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function pn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var mn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return w(this.flags_,1)}set isDisposed(e){this.flags_=T(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=T(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=T(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),_n())}runReaction_(){if(!this.isDisposed){on(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}j.trackingContext=e,sn()}}track(e){if(this.isDisposed)return;on();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=j.trackingContext;j.trackingContext=this;let i=Rt(this,e,void 0);j.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Vt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),sn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(j.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;j.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(on(),Vt(this),sn())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[E]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function hn(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}}let gn=e=>e();function _n(){j.inBatch>0||j.isRunningReactions||gn(vn)}function vn(){j.isRunningReactions=!0;let e=j.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}j.isRunningReactions=!1}let yn=b(`Reaction`,mn);function M(e){let t=gn;gn=n=>e(()=>t(n))}function bn(){return!!j.spyListeners.length}function xn(e){if(!j.spyListeners.length)return;let t=j.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return j.spyListeners.push(e),d(()=>{j.spyListeners=j.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=Ce(N),kn=Ce(`action.bound`,{bound:!0}),An=Ce(En,{autoAction:!0}),jn=Ce(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return Xe(e,Ee)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Ee(e?An:On,t,r);if(p(t))return xt(t.name||Dn,t,e);if(p(r))return xt(t,r,e);if(m(t))return Mn(Ce(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return St(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new mn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new mn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||pe,_=new mn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=Tt(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?Mi(t,n):Mi(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Zt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;j.enforceActions=e,j.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,j.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&M(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),gi(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=ae(t);return Fi(()=>{let t=Ei(e,i)[E];ne(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Mi(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Mi(e,t))}function er(e){let t={name:e.name_};return en(e)&&(t.observers=Array.from(tn(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return Xe(e,je)}let or=Oe(`flow`),sr=Oe(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return je(or,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++nr,a=Pn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(gi(e)||fi(e)||kt(e))i=Ni(e);else if(ki(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return jt(e);if(ki(e)===!1)return!1;let r=e[E];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Mi(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(gi(e)||fi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(ki(e)){var r,i;let n=e[E];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return ki(e)||!!e[E]||ce(e)||yn(e)||jt(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(ki(e))return e[E].keys_();if(gi(e)||xi(e))return Array.from(e.keys());if(fi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(ki(e))return Cr(e).map(t=>e[t]);if(gi(e))return Cr(e).map(t=>e.get(t));if(xi(e))return Array.from(e.values());if(fi(e))return e.slice();n(6)}function Tr(e){if(ki(e))return Cr(e).map(t=>[t,e[t]]);if(gi(e))return Cr(e).map(t=>[t,e.get(t)]);if(xi(e))return Array.from(e.entries());if(fi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!xi(e)){on();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{sn()}return}ki(e)?e[E].set_(t,r):gi(e)?e.set(t,r):xi(e)?e.add(t):fi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),on(),t>=e.length&&(e.length=t+1),e[t]=r,sn()):n(8)}function Dr(e,t){ki(e)?e[E].delete_(t):gi(e)||xi(e)?e.delete(t):fi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(ki(e))return e[E].has_(t);if(gi(e)||xi(e))return e.has(t);if(fi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(ki(e))return e[E].get_(t);if(gi(e))return e.get(t);if(fi(e))return e[t];n(11)}}function Ar(e,t,r){if(ki(e))return e[E].defineProperty_(t,r);n(39)}function jr(e){if(ki(e))return e[E].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=Ni(e);if(fi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(gi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(xi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(ki(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Yr(i,t)}function Pr(e,t,n,r){return Fr(Ni(e,t),n,r)}function Fr(e,t,n){if(jt(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ut();t({observableKind:`computed`,debugObjectName:e.name_,type:ni,object:e,newValue:a,oldValue:i}),Wt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ni,newValue:e.value_,oldValue:void 0}),Yr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(kt(e)||jt(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(fi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(xi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(gi(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){on();try{return e.apply(t)}finally{sn()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[E].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Bn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Vr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Ur(e){return e[E]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=Ei(e,t),(n=e[E]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function P(e,t){let r=Ut();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Wt(r)}}function Jr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Yr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Xr(e,t){let n=Ut(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Wt(n)}}function Zr(e,t,n){return Fi(()=>{let r=Ei(e,n)[E];ne(t).forEach(e=>ei(r,e,t[e]))}),e}let Qr=Symbol(`mobx-keys`);function $r(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Ei(e,r)[E];if(!e[Qr]){let t=Object.getPrototypeOf(e),n=new Set([...ne(e),...ne(t)]);n.delete(`constructor`),n.delete(E),v(t,Qr,n)}e[Qr].forEach(e=>ei(n,e,t&&e in t?t[e]:!0))}),e)}function ei(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;ji(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}Ai(e,r,t)}let ti=`splice`,ni=`update`,ri={get(e,t){let n=e[E];return t===E?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ie(oi,t)?oi[t]:e[t]},set(e,t,n){let r=e[E];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ii=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new se(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){It(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=P(this,{object:this.proxy_,type:ti,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Jr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ni,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Xr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Jr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ti,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Xr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){It(this.atom_);let r=n[e];if(Kr(this)){let n=P(this,{type:ni,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function ai(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ii(n,t,r);y(i.values_,E,i);let a=new Proxy(i.values_,ri);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var oi={clear(){return this.splice(0)},replace(e){let t=this[E];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[E];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[E].spliceWithArray_(e,t,n)},push(...e){let t=this[E];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[E].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[E];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return j.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[E],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};si(`at`,ci),si(`concat`,ci),si(`flat`,ci),si(`includes`,ci),si(`indexOf`,ci),si(`join`,ci),si(`lastIndexOf`,ci),si(`slice`,ci),si(`toString`,ci),si(`toLocaleString`,ci),si(`toSorted`,ci),si(`toSpliced`,ci),si(`with`,ci),si(`every`,li),si(`filter`,li),si(`find`,li),si(`findIndex`,li),si(`findLast`,li),si(`findLastIndex`,li),si(`flatMap`,li),si(`forEach`,li),si(`map`,li),si(`some`,li),si(`toReversed`,li),si(`reduce`,ui),si(`reduceRight`,ui);function si(e,t){typeof Array.prototype[e]==`function`&&(oi[e]=t(e))}function ci(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function li(e){return function(t,n){let r=this[E];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function ui(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let di=b(`ObservableArrayAdministration`,ii);function fi(e){return h(e)&&di(e[E])}let pi={},mi=`delete`;var hi=class{constructor(e,t=me,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[E]=pi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=le(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!j.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),ge,`${this.name_}.${C(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(Kr(this)){let r=P(this,{type:n?ni:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(It(this.keysAtom_),Kr(this)&&!P(this,{type:mi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Jr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:mi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Xr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=bn(),i=Jr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ni,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Xr(this,a),r&&wn()}}addValue_(e,t){It(this.keysAtom_),zr(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${C(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Jr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Xr(this,i),n&&wn()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return gi(e)&&(e=new Map(e)),zr(()=>{g(e)?te(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):ee(e)?(x(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Ht(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=vi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},gi=b(`ObservableMap`,hi);function _i(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function vi(e){if(ee(e)||gi(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let yi={};var bi=class{constructor(e,t=me,n=`ObservableSet@`+u()){this.name_=void 0,this[E]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=le(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Ht(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(It(this.atom_),Kr(this)){let t=P(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Jr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Xr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!P(this,{type:mi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Jr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:mi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Xr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return Si({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Si({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return xi(e)&&(e=new Set(e)),Array.isArray(e)||S(e)?zr(()=>{let t=S(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},xi=b(`ObservableSet`,bi);function Si(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let Ci=Object.create(null),wi=`remove`;var Ti=class{constructor(e,t=new Map,r,i=We){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new se(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof At)return n.set(t),!0;if(Kr(this)){let n=P(this,{type:ni,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=Jr(this),i=bn(),a=r||i?{type:ni,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Xr(this,a),i&&wn()}return!0}get_(e){return j.trackingDerivation&&!ie(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ie(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!j.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,ge,`${this.name_}.${C(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);ji(this,n,e);let i=n.extend_(this,e,t,r);return i&&Ai(this,n,e),i}defineProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{sn()}return!0}defineObservableProperty_(e,t,n,r=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Oi(e),s={configurable:j.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{sn()}return!0}defineComputedProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=Oi(e),o={configurable:j.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new At(t)),this.notifyPropertyAddition_(e,void 0)}finally{sn()}return!0}delete_(e,t=!1){if(It(this.keysAtom_),!ie(this.target_,e))return!0;if(Kr(this)&&!P(this,{object:this.proxy_||this.target_,name:e,type:wi}))return null;try{var n;on();let r=Jr(this),a=bn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof Ot&&(s=o.value_),dn(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:wi,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Xr(this,t),a&&wn()}}finally{sn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Jr(this),i=bn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&Sn(n),r&&Xr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),ne(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Ei(e,t){if(t&&ki(e)&&n(`Options can't be provided for already observable objects.`),ie(e,E))return Ni(e)instanceof Ti||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,E,new Ti(e,new Map,String(r),at(t))),e}let Di=b(`ObservableObjectAdministration`,Ti);function Oi(e){return Ci[e]||(Ci[e]={get(){return this[E].getObservablePropValue_(e)},set(t){return this[E].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[E]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!be(t)&&ie(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Mi(e,t){if(typeof e==`object`&&e){if(fi(e))return t!==void 0&&n(23),e[E].atom_;if(xi(e))return e.atom_;if(gi(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(ki(e)){if(!t)return n(26);let r=e[E],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ce(e)||jt(e)||yn(e))return e}else if(p(e)&&yn(e[E]))return e[E];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(ce(e)||jt(e)||yn(e)||gi(e)||xi(e))return e;if(e[E])return e[E];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=Mi(e,t);else if(zn(e))return e.name;else n=ki(e)||gi(e)||xi(e)?Ni(e):Mi(e);return n.name_}function Fi(e){let t=Ut(),n=Et(!0);on();try{return e()}finally{sn(),Dt(n),Wt(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(ie(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return fi(e)?e.slice():ee(e)||gi(e)||S(e)||xi(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:E}),e.$mobx=E,e.FlowCancellationError=rr,e.ObservableMap=hi,e.ObservableSet=bi,e.Reaction=mn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Gt,e._allowStateReadsStart=A,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=wt,e._getAdministration=Ni,e._getGlobalState=Qt,e._interceptReads=pr,e._isComputingDerivation=Ft,e._resetGlobalState=$t,e._startAction=Ct,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=pe,e.compareIdentity=ue,e.compareShallow=fe,e.compareStructural=de,e.computed=k,e.computedStruct=gt,e.configure=Yn,e.createAtom=le,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Mi,e.getDebugName=Pi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=kt,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=fi,e.isObservableMap=gi,e.isObservableObject=ki,e.isObservableProp=Sr,e.isObservableSet=xi,e.keys=Cr,e.makeAutoObservable=$r,e.makeObservable=Zr,e.observable=O,e.observableDeep=dt,e.observableRef=lt,e.observableShallow=ut,e.observableStruct=ft,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=hn,e.override=ye,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Ht,e.values=wr,e.when=Br})),xb=Te(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=yb():t.exports=bb()}))();function Sb(e){if(Array.isArray(e))return Object.freeze(e.map(Sb));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Sb(r);return Object.freeze(t)}return e}function Cb(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function wb(e){return typeof e==`string`?e:String(e)}function Tb(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function Eb(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var Db=class extends Error{constructor(e,t){super(t),this.variable=e}};function Ob(e){return e instanceof Db||e instanceof Error&&e.cause!==void 0&&Ob(e.cause)}var kb=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Rb(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Ab=class extends kb{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},jb=class extends kb{name=`EvalError`;kind=`EvalError`},Mb=class extends jb{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=zb(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},Nb=class extends jb{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},Pb=class extends jb{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},Fb=class extends Pb{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},Ib=class extends jb{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Lb=class extends jb{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Rb(e,t){let n=e.split(`
|
|
54
|
+
`?[t+1,0]:[t,n+Zo(e)],a+=Zo(e),{glyph:e,cell:r}})}})}function $f(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function ep(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||$f(e.style);return t.flatMap(({glyph:e,cell:t})=>t!==void 0&&(e.trim()!==``||n)?[t]:[])}),s=e.flatMap(({segment:e,look:t})=>t!==void 0&&e.text.trim()!==``&&!hu(t.style.anchor,Sd)?[t.pair]:[]),c=[...new Map(s.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],l=e=>c.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{cells:()=>a??=o(),pairs:c,colors:new Set([...l(`fg`),...l(`bg`)]),fills:new Set(l(`bg`)),depth:n,theme:r}}function tp(e,...t){let n=new Set(t),r=e=>wd(e.anchor,n),i=({fg:e,bg:t})=>e||t,a=e=>({...e,cells:()=>e.cells().filter(e=>i(r(e)))});return t=>au.map(e(a(t)),e=>(t,n)=>{let a=r(n);if(!i(a))return t;let o=e(t,n);return{fg:a.fg?o.fg:t.fg,bg:a.bg?o.bg:t.bg}})}function np(e,t){return t?{fg:e.bg,bg:e.fg}:e}function rp(e,t,n,r){let i=t.bg.compositeOver(Cs),a=t.fg.compositeOver(i);return{fg:B.matchMove(e.fg,a,n,r,!0),bg:B.matchMove(e.bg,i,n,r,!1)}}function ip(e,t){return ap(e.color,t.color,!0)&&ap(e.bgcolor,t.bgcolor,!1)}function ap(e,t,n){return e===t||op(e,n)===op(t,n)}function op(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function sp(e,t){return cp(e.fg,t.fg)&&cp(e.bg,t.bg)}function cp(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const lp=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),up=e=>e*e*e*(e*(e*6-15)+10),dp=(e,t,n)=>e+n*(t-e);function fp(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function pp(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=up(e),u=up(t),d=up(n),f=lp[o]+s,p=lp[f]+c,m=lp[f+1]+c,h=lp[o+1]+s,g=lp[h]+c,_=lp[h+1]+c;return dp(dp(dp(fp(lp[p],e,t,n),fp(lp[g],e-1,t,n),l),dp(fp(lp[m],e,t-1,n),fp(lp[_],e-1,t-1,n),l),u),dp(dp(fp(lp[p+1],e,t,n-1),fp(lp[g+1],e-1,t,n-1),l),dp(fp(lp[m+1],e,t-1,n-1),fp(lp[_+1],e-1,t-1,n-1),l),u),d)}function mp(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*pp(e*r,t*r,n*r),o+=a,a/=2}return i/o}function hp(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function gp(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const _p=Array.from({length:48},(e,t)=>(t+1)/48);function vp(e,t){return Math.min(Ts(e.fg,e.bg),4.5)-(t===z.TRUECOLOR?.01:0)}const yp=[`fg`,`bg`];function bp({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>yp.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>V.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=yp.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=vp(r,t),c=(t,n)=>Dp(i,r[t],(t===a?e:o)*n);return _p.every(e=>{let i=Yf.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return Ts(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function xp(e,t){let n=new WeakMap;return Tp(wp(e,r=>{let i=t??r.colors,a=[Sp(r),`|`,...i].join(` `),o=n.get(r.theme)??new Go;return n.set(r.theme,o),o.get(a,()=>bp(r,i,e.touch))}))}function Sp({depth:e,pairs:t}){return[e,...t.map(Cp)].join(` `)}function Cp({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function wp(e,t){return n=>{let r=t(n);return au.continuous(t=>{let i=e.field(t,n);return({fg:t,bg:n},a)=>{let o=Math.round(jp(i(a))*48)/48,s=(t,n)=>Dp(e.touch,t,(n?0:r.get(t.hex)??0)*o);return{fg:s(t,a.terminal.fg),bg:s(n,a.terminal.bg)}}})}}function Tp(e){return t=>Ep(t.depth)?au.constant(e=>e):e(t)}function Ep(e){switch(e){case z.DEFAULT:case z.STANDARD:case z.WINDOWS:return!0;case z.EIGHT_BIT:case z.TRUECOLOR:return!1}}function Dp(e,t,n){return n===0?t:e(t,n)}function Op(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}const kp={shimmer:{seconds:109,ease:ql.linear,swing:.9},pulse:{seconds:43,ease:ql.linear,swing:.85},sparkle:{seconds:139,ease:ql.linear,swing:.95},wheel:{seconds:907,ease:ql.linear,swing:1},fade:{seconds:20,ease:ql[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:ql[`ease-in-out`],swing:1}},Ap={sun:new R(255,228,176),firefly:new R(222,245,140)},jp=e=>Math.min(1,Math.max(0,e));function Mp(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new V((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Np(e){let t=V.fromRgba(e);return(e,n)=>{let r=V.fromRgba(e);return Mp(r,new V(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Pp=(e,t)=>t*e[e.length-1][0];function Fp(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function Ip(e,t,n){let r=Pp(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Fp(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const Lp=[[.24,1],[.6,0]];function Rp(e,t,n){Op(e);let r=.9+.2*hp(n,3.1),i=t=>.1*pp(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Np(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*gp(-.5,.5,pp(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const zp=e=>Math.abs(e)>=1?0:(1-e*e)**3;function Bp(e,t,n,r){Op(e);let i=e.seconds,a=i/2,o=e=>gp(-.4,.4,pp(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(hp(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*hp(e,8.5+r))),p=i*u/80*(c+l*hp(e,5.5+r)),m=jp((n-(e+s*hp(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*pp(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((pp(e,t,n)/.8)**2));return{touch:Np(n),field:(n,i)=>{let[a,o]=Kp(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*zp((i.col-a-n)/t));let c=i.row+r,l=.8*pp(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function Vp(e,t,n){Op(e);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*pp(e*1.7+.2,.3+t*2.9,.5+n),l=i+hp(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=hp(u,s+1)<.15?0:1,f=.5+.5*hp(u,s+2),p=hp(u,s+3)*(1-Pp(Lp,f)),m=l/r-u-p;return{x:a+c*8+5*(2*hp(u,s+4)-1)+5*f*(2*hp(u,s+5)-1)*Ip(Lp,m,f)+1.5*pp(s,.1,i*.035),y:o+t*3+.6*pp(s,2.2,i*.035),glow:d*Fp(Lp,m,f)}};return{touch:Np(t),field:(t,n)=>{let r=n.cells(),[s,c]=Kp(r.map(e=>e.col)),[l,u]=Kp(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*zp(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Hp(e,t){return n=>{let r=V.fromRgba(n.theme.backgroundColor);return au.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-jp(a(n)));if(i===0)return e;let o=Mp(V.fromRgba(e.bg),r,i);return{fg:Mp(V.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Up(e){let t=new Map;return n=>{let r=`${n.row}:${n.col}`,i=t.get(r)??jp(.5+1.1*mp(n.col*.09+1.4*pp(n.col*.035,n.row*.2+2.6,e+.5),n.row*.45,e,3));return t.set(r,i),i}}function Wp(e,t){let n=t=>t>=e.seconds;return{effect:r=>{let i=t(r);return{at:e=>i.at(e),nextChange:e=>n(e)?1/0:i.nextChange(e),lastChange:t=>n(t)?e.seconds:i.lastChange(t)}},done:n}}function Gp(e,t){let n=new Map,r=e=>`${e.row}:${e.col}`;return i=>{let[a,o]=Kp(i.map(t)),s=(o>a?.55:0)*e.seconds,c=iu.once(0,e.seconds-s),l=e=>{let n=o>a?jp((t(e)-a)/(o-a)):0;return{along:n,progress:e=>c(e-n*s)}};for(let e of i){let t=r(e);n.set(t,n.get(t)??l(e))}return e=>n.get(r(e))??l(e)}}function Kp(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function qp(e,t){Op(e);let n=Gp(e,Up(1.7+t));return Wp(e,Hp((t,r)=>{let i=n(r.cells());return n=>e.ease(i(n).progress(t))},e.swing))}const Jp={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function Yp(e,t){Op(e);let n=Up(9.3+t),r=Gp(e,Up(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Jp;return Wp(e,Hp((t,u)=>{let d=r(u.cells());return r=>{let{along:u,progress:f}=d(r),p=e.ease(f(t)),m=jp((p-a)/(o-a)),h=i*gp(s,c,n(r))*(1-l+l*u)*Math.sin(Math.PI*m)**2;return 1-p+h}},e.swing))}const Xp=[211,337];function Zp(e,t){Op(e);let n=e.seconds,r=e=>hp(Number.parseInt(e.slice(1),16)*1e-4,17.3+t),i=(e,n)=>pp(n/Xp[0],5.9+97*e,t)+.5*pp(n/Xp[1],2.3+89*e,t+7.1),a=(t,a)=>{let o=r(t);return 360*a/n+e.swing*180*((i(o,a)-i(o,0))/1.5)},o=new WeakMap;return Tp(e=>{let{colors:t,fills:n,depth:r,theme:i}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=o.get(i)??new Go;o.set(i,u);let d=u.get(Sp(e),()=>rm(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),f=om(r,i);return au.continuous(e=>{let t=new Map,n=(t,n)=>{let i=Qp(t,a(n,e));return sm(i.looks,t,r===z.TRUECOLOR?i.either.map(im):f,d.get(l(t,n))??em)},i=(e,r)=>{let i=t.get(l(e,r))??n(e,r);return t.set(l(e,r),i),i};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,t,n,r)=>t?i(e,c(e,n,r)):e;return{fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Qp(e,t){if(t===0)return{looks:e,either:[e]};let n=V.fromRgba(e),r=ws(e),i=e=>new V(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=ws(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const $p=e=>Math.log(Ts(e,new R(0,0,0))),em={lo:-1/0,hi:1/0},tm={lo:1/0,hi:-1/0},nm=Math.log(1.031);function rm(e,t,n){let r=new Map;for(let i of e.filter(e=>vp(e,t)>1)){let e=(Math.log(Ts(i.fg,i.bg))-Math.log(vp(i,t)))/yp.filter(e=>n(i,e)!==void 0).length;for(let t of yp){let a=n(i,t);if(a===void 0)continue;let[o,s]=[$p(i[t]),$p(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??em;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<nm?tm:{lo:t,hi:n}]))}const im=e=>({color:e,looks:V.fromRgba(e),stop:$p(e)}),am=new WeakMap;function om(e,t){let n=B.indexed(e,t),r=am.get(n)??n.map(([,e])=>im(e));return am.set(n,r),r}function sm(e,t,n,{lo:r,hi:i}){return cm(e,[im(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function cm(e,t){let n=V.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}const lm={loops:{shimmer:(e,t=kp.shimmer)=>xp(Bp(t,24,Ap.sun,e.z)),pulse:(e,t=kp.pulse)=>xp(Rp(t,Ap.sun,e.z)),sparkle:(e,t=kp.sparkle)=>xp(Vp(t,Ap.firefly,e.z)),wheel:(e,t=kp.wheel)=>Zp(t,e.z)},transitions:{fade:(e,t=kp.fade)=>qp(t,e.z),dissolve:(e,t=kp.dissolve)=>Yp(t,e.z)}};var um=class{beat;width;_shown;constructor(e){this.beat=ru(e.map(e=>e.seconds));let t=e.map(e=>Jf(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}};function dm(e,t){return e.at(t).copy().stylize(new H({nextChange:e.nextChange(t)}))}function fm(e,t){let n=[...Hu(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const pm={segments:[],width:0},mm={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function hm(e,t){return mm[e](t)}function gm(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var _m=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}contents(){return this.items}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>fm(Ed(t),e)),o=n=>i?fm(Td(i,null,t[n],{index:n}),e):pm,s=n=>i?fm(Td(i,t[n],null,{index:n+1}),e):pm,c=(n,r)=>i?fm(Td(i,t[n],t[r],{index:r}),e):pm,l=[],u=null,d=r>0?{segments:[new W(` `.repeat(r))],width:r}:pm;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=hm(p,i),o=gm(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new W(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new W(` `.repeat(e)))}yield*t.blocks[e].segments}yield W.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=fm(t[i],e).width,o=this.joiner?fm(Td(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?fm(Td(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=fm(Td(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=fm(Td(this.joiner,null,t[0],{index:0}),e).width,r+=fm(Td(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function vm(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const ym=[`primary`,`secondary`,`accent`],bm=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],xm={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},Sm=(e,t)=>`${e}${xm[t]}`,Cm=(e,t,n,r)=>th(e,n,r),wm=(e,t,n,r)=>rh(e,Gm(e,`text-${t}`),n,r),Tm=e=>({tones:[bm[e],bm[e+2],bm[e+1]],text:Cm}),Em={muted:{tones:[`muted`],text:wm},deepest:Tm(0),deeper:Tm(1),middle:Tm(2),brighter:Tm(3),brightest:Tm(4)},Dm=1/0,Om={accent:{hues:[`secondary`,`accent`],run:Dm},duo:{hues:[`primary`,`secondary`],run:Dm},mono:{hues:[`primary`],run:Dm},alt:{hues:[`secondary`,`accent`],run:3}},km=e=>e.variation.hues.flatMap(t=>e.shade.tones.map(e=>({hue:t,shade:e}))),Am=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},jm=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Mm=e=>typeof e==`string`&&jm.includes(e),Nm={"van-der-corput":Am,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Pm=e=>Nm[e??`van-der-corput`],Fm=(e,t)=>Math.floor(e*t),Im=(e,t)=>Math.round(e*t)%t;function Lm(e){return e===void 0?0:e.distribution(e.index,e.count)}function Rm(e,t,n){let r=e[n(Lm(t),e.length)];if(r===void 0)throw Error(`vocabularySelect: empty vocabulary`);return r}function zm(e){let t=e.findIndex(e=>e.axis===`cell`),n=t===-1?e:e.slice(0,t);return{row:n.at(-1),cell:e[n.length]}}const Bm=(e,t)=>Fm(Lm(t),e.hues.length);function Vm(e,t){let{row:n,cell:r}=zm(t);return Hm(e,n,r)}function Hm(e,t,n){let{hues:r,run:i}=e.variation,a=n===void 0?0:Math.floor(n.index/i),o=r[(Bm(e.variation,t)+a)%r.length];if(o===void 0)throw Error(`decorEntryFor: empty variation`);return{hue:o,shade:Rm(e.shade.tones,n,Im)}}function Um(e,t){let{row:n,cell:r}=zm(t),i=r===void 0?[void 0]:Array.from({length:r.count},(e,t)=>({...r,index:t}));return[...new Map(i.map(t=>Hm(e,n,t)).map(e=>[Sm(e.hue,e.shade),e])).values()].sort((e,t)=>ym.indexOf(e.hue)-ym.indexOf(t.hue)||Wm.indexOf(e.shade)-Wm.indexOf(t.shade))}const Wm=[...bm,`muted`];function Gm(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}const Km=(e,t)=>Gm(e,Sm(t.hue,t.shade)),qm=2.2,Jm=(e,t)=>t.map(t=>Km(e,t)),Ym=e=>t=>Gc(t,e),Xm=Ym(z.TRUECOLOR);function Zm(e,t,n,r){return Qm(e,`${t}|${n.map(e=>e.hex).join(`+`)}|${r}`,()=>$m(e,t,n,r))}const Qm=vm();function $m(e,t,n,r){let i=n.map(Xm),a=Gm(e,t),o=new R(0,0,0),s=new R(255,255,255),c=(e,t)=>V.fromRgba(a).mixAxes(V.fromRgba(e),{l:t,c:0,h:0,alpha:0}).toRgba(),l=e=>Array.from({length:12},(t,n)=>c(e,(n+1)/12)),u=l(o),d=[a,...l(s).flatMap((e,t)=>[e,u[t]])],f=e=>{let t=Ym(e),n=i.map(t);return e=>Math.min(1/0,...n.map(n=>Ts(t(e),n)))},p=f(z.TRUECOLOR),m=f(r),h=e=>Wc(e,r,(e,t)=>i.every(n=>Ts(e,t(n))>=qm)),g=e=>p(e)>=2.2&&h(e)!==void 0,_=(e,t)=>{let n=n=>Ts(Xm(n),e)-Ts(Xm(n),t),r=n(a)<0?o:s,i=r===o?1:-1,[l,u]=[0,1];for(let e=0;e<40;e++){let e=(l+u)/2;i*n(c(r,e))>0?u=e:l=e}return[c(r,l),c(r,u)]},v=()=>{let e=[...i].sort((e,t)=>ws(e)-ws(t));return e.slice(1).flatMap((t,n)=>_(t,e[n]))},y=d.find(g)??[...d,...v()].reduce((e,t)=>m(t)>m(e)?t:e),b=h(y)??y,ee=m(b);return{anchor:y,state:b,short:ee>=2.2?null:ee}}const eh=4.5;function th(e,t,n){return nh(e,`${t.hex}|${n}`,()=>{let r=Hc(t);return rh(e,[`background`,`foreground`].map(t=>Gm(e,t)).reduce((e,t)=>Ts(r,t)<Ts(r,e)?t:e),t,n)})}const nh=vm();function rh(e,t,n,r){return ih(e,`${t.hex}|${n.hex}|${r}`,()=>Uc(t,n,eh,r))}const ih=vm();function ah(e,t,n){return t.depth===0?Jm(e,t.ground):[...oh(e,t,n),sh(e,{...t,depth:t.depth-1},n).state]}const oh=(e,t,n)=>t.depth===0?[]:[Ch(e,{...t,depth:t.depth-1},n).plane],sh=(e,t,n)=>Zm(e,ph(t.hue,t.depth),ah(e,t,n),n),ch=e=>({...e,depth:e.depth+1}),lh=(e,t,{short:n},r)=>n===null?[]:[`theme "${e.name}": no open-trigger colour stands ${qm}:1 off every cell beside it — the nearest stands ${n.toFixed(2)}:1 as drawn at depth ${z[r]}; ${uh[t.depth===0?`bar`:`band`]} clears it`],uh={bar:`another shade or variation`,band:`another shade or style`},dh=(e,t,n)=>t>=mh.triggerPlane?[]:[`theme "${e.name}": an open band's plane stands ΔE ${t.toFixed(3)} off the trigger that opened it as drawn at depth ${z[n]}, under the ${mh.triggerPlane} that tells them apart; another style clears it`],fh={base:.42,perDepth:.14,cap:.75};function ph(e,t){return ym[(ym.indexOf(e)+t)%ym.length]}const mh={triggerPlane:.1,nestedPlane:.035};function hh(e,t,n){return gh(e,`${_h(t)}|${n}`,()=>{let r=sh(e,t,n),{state:i}=r,a=sh(e,ch(t),n),o=Dh(e,t,i,a,n),s=Wc(Ch(e,t,n).plane,n,(e,t)=>o.every(n=>n(e,t)));if(s===void 0)throw Error(`palette "${e.name}": the ${t.hue} band at depth ${t.depth} cannot keep its floors on the colours drawn at depth ${z[n]}`);let c=xh(e,t,{state:i,plane:s},a,n),l=Ym(n);return{state:i,plane:s,items:c,shortfalls:n===z.DEFAULT?[]:[...lh(e,t,r,n),...dh(e,vh(l(i),l(s)),n),...bh(e,yh(e,t,{state:i,items:c},n),n)]}})}const gh=vm(),_h=({hue:e,depth:t,ground:n})=>`${e}|${t}|${n.map(e=>Sm(e.hue,e.shade)).join(`+`)}`,vh=(e,t)=>V.fromRgba(e).deltaE(V.fromRgba(t)),yh=(e,t,{state:n,items:r},i)=>{let a=e=>[[`trigger`,e.state],[`low item`,e.items[0]],[`high item`,e.items[1]]],o=a({state:n,items:r}),s=t.depth===0?[]:a(hh(e,{...t,depth:t.depth-1},i));return[...o.flatMap(([e,t],n)=>o.slice(n+1).map(([n,r])=>({between:`an open band's ${e} and ${n}`,a:t,b:r}))),...s.map(([e,t])=>({between:`a trigger open in a band and that band's ${e}`,a:n,b:t}))]},bh=(e,t,n)=>{let r=Ym(n);return t.flatMap(({between:t,a:i,b:a})=>{let o=vh(r(i),r(a));return o>=.04?[]:[`theme "${e.name}": ${t} stand ΔE ${o.toFixed(3)} apart as drawn at depth ${z[n]}, under the ${kd} below which two cells in those colours are joined by a divider and read as one`]})};function xh(e,t,n,r,i){let a=Ch(e,t,i),o=ic(a.plane,a.state,.12),s=Sh(o,a.state,[r.anchor]),c=e=>(t,r)=>t.hex!==r(n.plane).hex&&e.every(e=>vh(t,r(e))>=.04),l=Ym(i),u=[n.state,r.state],d=Wc(o,i,c(u))??l(o);return[d,Wc(s,i,c([...u,d]))??l(s)]}function Sh(e,t,n){let r=[e,t,...n].map(e=>V.fromRgba(Xm(e))),i=e=>{let t=V.fromRgba(Xm(e));return Math.min(...r.map(e=>t.deltaE(e)))},a=Math.max(1,Math.abs(t.red-e.red),Math.abs(t.green-e.green),Math.abs(t.blue-e.blue)),o=e,s=0;for(let n=0;n<=a;n++){let r=ic(e,t,n/a),c=i(r);c>s&&([o,s]=[r,c])}return o}function Ch(e,t,n){return wh(e,`${_h(t)}|${n}`,()=>Th(e,t,n))}const wh=vm();function Th(e,t,n){let{anchor:r}=sh(e,t,n),i=Math.min(fh.cap,fh.base+fh.perDepth*t.depth),a=(t,n)=>ic(r,Gm(e,t),n),o=oh(e,t,n),s=e=>vh(Xm(r),Xm(e))>=mh.triggerPlane&&o.every(t=>vh(Xm(t),Xm(e))>=mh.nestedPlane),c=a(`background`,i);return{state:r,plane:[c,a(`foreground`,i),a(`background`,fh.cap),a(`foreground`,fh.cap),...Eh.toSorted((e,t)=>Math.abs(e-i)-Math.abs(t-i)).flatMap(e=>[a(`background`,e),a(`foreground`,e)])].find(s)??c}}const Eh=Array.from({length:12},(e,t)=>(t+1)/12);function Dh(e,t,n,r,i){let{hue:a,depth:o,ground:s}=t,c=t=>Ch(e,{hue:a,depth:t,ground:s},i).state,l=t=>Ch(e,{hue:a,depth:t,ground:s},i).plane,u=l(o),d=(e,t)=>vh(Xm(u),Xm(t))>=e?e:0,f=Ts(Xm(u),Xm(r.anchor))>=2.2?qm:0,p=(e,t)=>(n,r)=>vh(n,r(e))>=t;return[p(n,d(mh.triggerPlane,c(o))),(e,t)=>Ts(e,t(r.state))>=f,...o>0?[p(hh(e,{hue:a,depth:o-1,ground:s},i).plane,d(mh.nestedPlane,l(o-1)))]:[]]}function Oh(e,t,n,r){return Rm(hh(e,t,r).items,n,Fm)}const kh=e=>({kind:`bar`,decor:e,address:[]}),Ah=(e,t)=>({...e,address:[...e.address,t]}),jh=e=>({kind:`band`,band:e,address:[]});function Mh(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=Vm(r,i),o=Km(e,a),s;return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{hue:`accent`,depth:0,get ground(){return s??=Um(r,i)}}}}case`band`:{let{band:r,address:i}=t,a=Oh(e,r,zm(i).cell,n);return{tint:a,text:th(e,a,n),disclosure:{...r,depth:r.depth+1}}}}}const Nh=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function Ph(e){let t=typeof e==`string`?Nh.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const Fh=`textual-dark`;function Ih(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function Lh(){return fl()}function Rh(){return[`bar`,...Lh()]}let zh;function Bh(e){return zh??=new Set(Rh()),zh.has(e)}function Vh(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return Ih(e===void 0?null:a(e),t,a(n??r),r,a)}const Hh=[`style`,`palette`,`effect`];function Uh(e){return e!==void 0&&e.includes(`{{`)}function Wh(e,t,n,r,i){let a=Uh(n)?{kind:`expression`,source:n}:i(n??r.name);return Ih(e===void 0?null:i(e),t,a,r,i)}function Gh(e,t){return e.kind===`decided`?e:t(e.source)}const Kh=`none`;function qh(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function Jh(e,t){return qh(e,t)??qh(`none`,t)??{kind:`decided`,name:`none`,value:Sc}}function Yh(e,t,n,r){return Wh(e,t,n,Jh(Kh,r),e=>qh(e,r))}const Xh=`none`,Zh={style:Kh,palette:Fh,effect:Xh};function Qh(e,t,n){return`${e} rendered "${Zh[t]}": ${n}`}const $h=Object.freeze([Xh,...Object.keys(lm.loops)]),eg=Object.freeze([`bar`,...$h]);function tg(e){let t=$h.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function ng(e){return tg(e)??{kind:`decided`,name:`none`,value:`none`}}function rg(e,t,n){return Wh(e,t,n,ng(Xh),tg)}const ig=Object.freeze(Object.keys(Nf)),ag=[`powerline`,`capsule`,`plain`];function og(e){return ag.includes(e)}const sg=[`truecolor`,`256`,`ansi`,`none`];function cg(e){return Rs(e)??z.DEFAULT}const lg=Object.keys(Om),ug=Object.keys(Em),dg=`true`,fg=`false`,pg=[dg,fg],mg={min:0,max:16};function hg(e){return e===`true`?!0:e===`false`?!1:null}function gg(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const _g=[`vertical`,`horizontal`],vg={vertical:`row`,horizontal:`cell`};function yg(e){return e.id??e.name}function bg(e){return[...Cg(e)].flatMap(e=>e.kind===`segment`?[yg(e)]:[])}function xg(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Sg(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*Cg(e){yield e;for(let t of Dg(e))yield*Cg(t)}const wg=(e,t)=>`${e}.children[${t}]`,Tg=e=>`${e}.opens.body`;function*Eg(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*Eg(r,wg(t,n));else e.opens!==void 0&&(yield*Eg(e.opens.body,Tg(t)))}function Dg(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function Og(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const kg=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Ag(e){return e.kind===`file`||e.kind===`shell`}const jg=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Mg=[`fail`,`ignore`];function Ng(e){return e.missingData??`fail`}function*Pg(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const Fg=`theme`,Ig=`effect`,Lg=[Fg,Ig];function Rg(e){return{...e.settings,[Fg]:{label:Fg,domain:`theme`,default:e.palette??`bar`},[Ig]:{label:Ig,domain:eg,default:`bar`}}}function zg(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function Bg(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=zg(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Vg(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&Bh(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Hg(e){return String(e)}function Ug(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return gg(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Vg(e,r)?r:void 0}function Wg(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:Ug(n,o))??i}function Gg(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Kg=[`left`,`center`,`right`],qg=[`right`,`left`,`middle`];var Jg=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Qg(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function K(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=Yg(e,n,i);if(t===-1)return r===void 0?void 0:Xg(e,r);n=t,r=t}return r===void 0?void 0:Xg(e,r)}function Yg(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function Xg(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Zg(e,t){try{return _i(t),null}catch(n){if(!(n instanceof di))throw n;return`${e}:${Xg(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Qg(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
|
|
55
|
+
`)}function $g(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),r])}),null)}function e_(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),`default`])});return}return i}}function t_(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),r])});return}return i}}function n_(e,t,n){let r=t_(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Ph(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[...t.split(`.`),`palette`])});return}return r}}function r_(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${q(a)}`,line:K(e.source,[...t.split(`.`),r])});return}return a}}function i_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a_(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function q(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function o_(e,t,n,r){return i_(r)?(u_(e,n,r,t.noun,new Set(Object.keys(t.fields)),s_(e,t.removed??{},n,r)),c_(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${a_(r)}`,line:K(e.source,n.split(`.`))}),null)}function s_(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)d_(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function c_(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const l_=new Set;function u_(e,t,n,r,i,a=l_){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:K(e.source,[...t.split(`.`),o])})}function d_(e,t,n){return e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))}),null}function f_(e,t,n,r){if(!i_(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${a_(r)}`,line:K(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:K(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:K(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:K(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function p_(e,t,n,r){if(!i_(r))return e.issues.push({path:n,message:`${n} must be an object, got ${a_(r)}`,line:K(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${a_(i)}`,line:K(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:K(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return u_(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function m_(e,t,n){return{json:O_(E_(n),e,t),keys:new Set([e,...Object.keys(n)])}}function h_(e){return(...t)=>e()(...t)}function g_(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:K(n.source,o.split(`.`))}),null}return a}}function __(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>t_(e,t,r,n)}}function v_(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${a_(i)}`,line:K(e.source,[n])});return}return i}}}}function y_(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${q(o)}`,line:K(e.source,[i])});return}return o}}}}function b_(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${q(a)}`,line:K(e.source,[r])});return}return a}}}}function x_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>n_(e,t,r)}}function S_(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>$g(e,t,r,n)??void 0}}function C_(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function w_(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=$g(e,t,r,n);if(i===null)return;let a=C_(`${t}.${n}`,i);return a===null?i:d_(e,`${t}.${n}`,a)??void 0}}}function T_(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>r_(t,n,i,r,e)}}function E_(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function D_(e){return E_(e.fields)}function O_(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function k_(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function A_(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const j_={band:{setting:`experimentalBand`,label:`🧪 band (A)`,elsewhere:`the band above the prompt`},statusline:{setting:`experimentalStatusline`,label:`🧪 statusline (B)`,elsewhere:null},pane:{setting:`experimentalPane`,label:`🧪 tmux pane (C)`,elsewhere:`a tmux pane below`},tmuxStatus:{setting:`experimentalTmuxStatus`,label:`🧪 tmux status line (C)`,elsewhere:`the tmux status line`}},M_=Object.keys(j_),N_={by:`request`},P_=e=>`drawing.${e}`,F_={subscribers:0,fps:0,shown:!0},I_=(e,t)=>`feeds.${e}.${t}`;function L_(e){return Object.fromEntries(M_.map(t=>[t,e(t)]))}const R_=L_(()=>F_);function z_(e){return typeof e==`string`&&Object.hasOwn(j_,e)?e:null}const B_=(e,t,n=[])=>({label:e,place:t,previews:n}),V_=(e,t)=>({spec:T_(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e}}}),H_={spec:v_(),domain:`bool`,parse:hg},U_=e=>({spec:y_(e),domain:e,parse:t=>gg(t,e)});function W_(e,t,n,r={}){return{kind:`session`,...V_(e,r.optionDomain),floor:t,control:n,themeDefault:r.themeDefault??!1}}function G_(e,t){return{kind:`session`,...H_,floor:e,control:t,themeDefault:!1}}function K_(e,t,n){return{kind:`session`,...U_(e),floor:t,control:n,themeDefault:!1}}function q_(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const J_=e=>({kind:`text`,spec:e}),Y_={required:!1,json:{enum:[...sg]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${sg.join(`, `)}`,line:K(e.source,[...t.split(`.`),n])});return}return r_(e,t,r,n,sg)}},X_={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=t_(e,t,r,n);return Uh(i)?i:n_(e,t,r)}},Z_={required:!1,json:{anyOf:[{enum:[...$h]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Uh(i)?i:r_(e,t,r,n,$h)}},Q_=/^[^\r\n]*\S[^\r\n]*$/u,$_=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),ev={required:!1,json:{type:`string`,pattern:Q_.source,not:{pattern:$_.source}},parse:(e,t,n,r)=>{let i=t_(e,t,r,n);if(i===void 0||Q_.test(i)&&!$_.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:K(e.source,[...t.split(`.`),n])})}},tv=Object.fromEntries(M_.map(e=>[j_[e].setting,G_(!1,B_(j_[e].label,`toggles`))])),nv={palette:q_(`theme`,X_,{themes:`themes`},B_(`🎨 theme`,`door`)),preset:q_(`preset`,__(),{from:`presets`},B_(`▦`,`door`,[`layout`,`presetDelete`])),style:q_(`style`,__(),{from:`styles`},B_(`◐`,`gear`,[`palette`]),{themeDefault:!0}),effect:q_(`effect`,Z_,{from:$h},B_(`✨`,`look`)),endcaps:W_(ig,`powerline`,B_(`✦`,`look`),{optionDomain:`endcaps`}),variation:W_(lg,`accent`,B_(`🎼`,`gear`,[`layout`]),{optionDomain:`variations`,themeDefault:!0}),shade:W_(ug,`middle`,B_(`🔆`,`gear`,[`layout`]),{optionDomain:`shades`,themeDefault:!0}),transitions:G_(!1,B_(`fade in/out`,`look`)),autoWrap:G_(!0,B_(`wrap`,`config`)),padding:K_({...mg,step:1},1,B_(`padding`,`config`)),updateNotice:G_(!0,B_(`update notice`,`config`)),...tv,colorCompatibility:{kind:`config`,...V_(sg,`colorCompatibilities`),spec:Y_,floor:`truecolor`},default_empty_value:J_(__()),default_separator:J_(__()),menuGlyph:J_(ev)},rv=Object.entries(nv),iv=rv.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),av=rv.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),ov=rv.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),sv=rv.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function cv(e){return nv[e]}const lv=e=>cv(e).floor;function uv(e){let t=nv[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const dv=e=>`${e}.effective`,fv=e=>{let t=nv[e];return t.kind===`selection`?t.sessionKey:e},pv=Object.fromEntries(av.map(e=>{let t=fv(e);return[t,{configKey:e,sessionKey:t,effectiveVar:dv(t),...nv[e].control}]})),mv=Object.keys(pv),hv=Object.values(pv),gv=iv.filter(e=>nv[e].kind===`config`).map(e=>({configKey:e,effectiveVar:dv(e)})),_v=new Set(gv.map(e=>e.configKey)),vv=new Map([...hv,...gv].map(e=>[e.configKey,e.effectiveVar])),yv=new Map(hv.map(e=>[e.sessionKey,e.effectiveVar]));function bv(e){return Object.fromEntries(mv.map(t=>[t,e(t)]))}const xv=new Map(mv.map(e=>[pv[e].sessionKey,e])),Sv=[[0,31],[127,159],[8234,8238],[8294,8303]];function Cv(e){return Sv.some(([t,n])=>e>=t&&e<=n)}function wv(e){let t=``;for(let n of e)t+=Cv(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function Tv(e,t){let n=wv(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const Ev=`\x1B[38;2;255;255;255m`,Dv=`\x1B[48;2;200;40;40m`,Ov=`\x1B[0m`;function kv(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const Av={fg:kv(Ev),bg:kv(Dv)},jv={fg:kv(`\x1B[38;2;0;0;0m`),bg:kv(`\x1B[48;2;220;160;40m`)},Mv=new Cu({"strip.separator":`default`,"strip.rail":`default`});function Nv(e){return Mv.resolve(e)}const Pv={kind:`still`},Fv=Symbol(`bar`);function Iv(e){return e.name!==Xh}function Lv(e,t){return n=>au.map(au.all(t.map(({t,effect:r})=>pu.run(pu.play(e-t),r(n)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const Rv=xl;function zv(e,t){let n=new ac(t,Rv.foregroundColor,Rv.ansiColors,Rv.palette);return t=>e({...t,theme:n})}function Bv(e,t){return n=>tp(()=>e(n),...t)(n)}function Vv(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const Hv=4096;var Uv=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Xh,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(({passage:e})=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:Fv,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision&&u.source.width===n.source.width?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h=[],g={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m,leaves:h},_=(e,n,{ground:r})=>{let i=lm.transitions[e]({z:Vv(`${this.key}@${n}`)*Hv});return{name:e,since:t,transition:{effect:zv(i.effect,r),done:e=>i.done(e)}}},v=({since:e,transition:n})=>n.done(t-e),y=(e,t,n)=>({drawing:t,passage:f===null?null:n===void 0||n.passage?.name===`dissolve`?_(`fade`,e,t):n.passage!==null&&!v(n.passage)?n.passage:null}),b=(e,t)=>{if(t===void 0||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return v(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:_(`dissolve`,e,r)}},ee=(e,r)=>{if(p.has(e))throw Error(`placement "${e}" was reached twice in one frame`);let i=f?.get(e),{drawing:a,deeper:o}=n.returned(e,r),s=a===null?b(e,i):y(e,a,i);return s===void 0?r:(p.set(e,s),s.passage!==null&&(s.passage.name===`fade`?m:h).push({placement:e,t:t-s.passage.since}),a===null?[...s.drawing.own,...o]:r)},x=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},S=(e,t)=>{let n=c.get(e)??new Map;c.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=s.get(e)?.get(t.scope),a=i?.name===t.name,o=Vv(t.scope===Fv?e:`${e}@${t.scope}`),l=a?i.effect:lm.loops[t.name]({z:o*Hv});return g[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:l}),l},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:x(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},ne=e=>{let n=new Map;for(let{owner:t,placement:r}of e){let e=n.get(r.id);e===void 0?n.set(r.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=p.get(e)?.passage??null;return r===null?[]:[{t:t-r.since,effect:tp(r.transition.effect,...n)}]})};return{placed:d===`off`?(e,t)=>t:ee,row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?te(t):[{...i,owners:void 0}]).filter(Iv),r=ne(t);if(n.length===0&&r.length===0)return Pv;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:e=>new Yf(e,Lv(i.t,[...n.map(e=>{let t=S(a,e);return{t:e.t,effect:e.owners===void 0?t:Bv(t,e.owners)}}),...r]),{t:i.t,key:a,theme:Rv})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=g}}}},Wv=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new Uv(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function Gv(e,t){let n=Ls(t.colorSystem),r=[...Hu(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:Mv,colorSystem:n.colorSystem,onStyleError:e=>{throw e}})];return{text:Ff(r,n),moves:Number.isFinite(W.nextChange(r))}}const Kv=new Map;function qv(e){let t=Kv.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>`cap`in t?t:{...t,glyph:e});return{seam:n,divider:n}},{seam:r,caps:i}=Nf.plain,a=new tf({glyph:n(r.glyph),ascii:r.ascii},i);return Kv.set(e,a),a}function Jv(e,t){return e===`plain`&&t!==void 0?qv(t):Nf[e]}const Yv=new Map;function Xv(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=Yv.get(t);if(n!==void 0)return n;let r=Jv(e.endcaps,e.separator),i=e=>new G(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=e=>new G(Gv(new Dd(e,r),{colorSystem:null}).text.replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return Yv.set(t,s),s}function Zv(e){return Xv(e).chrome}function Qv(e){return Xv(e).seam}const $v=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function ey(e){return[...new Set(e.match($v)??[])].join(``)}function ty(e){let t=Jv(e.endcaps,e.separator),n=e=>new G(`x`,{end:``,style:new H({bgcolor:e})});return ey(Gv(new Dd([n(`#101010`),n(`#202020`),n(`#202020`)],t),{colorSystem:null}).text)}function ny(e,t,n=Pv){if(e.length===0)return{text:``,moves:!1};let r=Jv(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new _m([...e],{joiner:r}):new Dd([...e],r),s=Gv(n.kind===`still`?o:n.wrap(o),a);if(!s.text.endsWith(`
|
|
56
|
+
`))throw Error(`drawStripCells: rich-js strip output did not end its last line`);return{text:s.text.slice(0,-1),moves:s.moves}}function ry(e,t){return ny(e,t).text}function iy(e){return Math.min(20,e??20)}const ay={heading:`ERROR`,glyph:`⚠`,colors:Av},oy={heading:`WARNING`,glyph:`⚠`,colors:jv},sy={heading:`UPDATE`,glyph:`⬆`,colors:jv},cy={heading:`LANES`,glyph:`🧪`,colors:jv};function ly(e,t){return{text:wv(e),link:t}}function uy(e,t,n){let[r,...i]=[dy(e,ay,yr),t,dy(n,oy,br)].flat();return r===void 0?null:{channels:[r,...i]}}function dy(e,t,n){let r=Hr([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>ly(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function fy(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
|
|
57
|
+
`)}function py(e,t,n,r){if(t===null)return e;let i=gy(r),a=hy(t,i),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[vy(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
|
|
58
|
+
`);return e?`${l}\n${e}`:l}function my(e,t){return hy(e,gy(t)).join(`
|
|
59
|
+
`)}function hy(e,t){return e.channels.flatMap(e=>_y(e,t))}function gy(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}function _y(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Qo(Math.max(2,t.width-1)),i=(e,t)=>new G(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>ry([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>rs(e,r)).map(e=>i(e,t))})],t).split(`
|
|
60
|
+
`))}function vy(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:o,failedConfigFile:s}=t,c=new H({bgcolor:i.bg,color:i.fg}),l=(e,t)=>new G(e,{style:t,end:``,overflow:`ignore`}),u=n>0?[l(`${n} more rows · `,c),o.kind===`file`?l(`open full text`,c.withLink(a(o.path).href)):l(`full text unavailable: ${wv(o.reason)}`,c)]:[],d=s===null?[]:[l(`${u.length>0?` · `:``}open `,c),l(wv(s),c.withLink(a(s).href))],f=[l(`↳ `,c),...u,...d.slice(0,-1)],p=f.reduce((e,t)=>e+t.cellLength,0),m=d.slice(-1).map(e=>e.truncate(Math.max(1,r.width-p),{mode:`middle`})),h=G.fromFragments([...f,...m]).truncate(r.width);return h.overflow=`ignore`,ry([h],r)}var J=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const yy=new Map;function by(e){let t=Sy(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function xy(e,t){return e===`bar`?t:by(e)}function Sy(e){let t=yy.get(e);if(t!==void 0)return t;let n=pl(e);return n===null?null:(yy.set(e,n),n)}function Cy(e,t){return wy(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Tl(e,t))}const wy=vm();function Ty(e){let t=Sy(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Ey(e,t,n){let r=Ty(e);return r===null?(n(Qh(t,`palette`,`"${e}" names no installed theme${Ph(e)}`)),Oy()):r}function Dy(e,t,n){return Wh(e,t,n,Oy(),Ty)}function Oy(){return{kind:`decided`,name:Fh,value:by(Fh)}}const ky=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ay(e){return`#${e+1}`}const jy={rows:{}};function My(e){return`rows`in e}function Ny(e){return Object.fromEntries(e.map((e,t)=>[Ay(t),e]))}function Py(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Ny(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Ny([n])}}function Fy(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Iy(e){return My(e)?Fy(e):e}function*Ly(e,t){if(!My(e)){yield*Eg(e,t);return}yield[Fy(e),t];for(let[n,r]of Object.entries(e.rows))yield*Eg(r,`${t}.rows.${n}`)}function Ry(e,t){return My(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Py(e)}function zy(e){if(!My(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const By=`default`,Vy={};function Hy(e){return[...new Set([By,...Object.keys(e)])]}function Uy(e,t,n){return Vh(void 0,e,t,By,n)}function Wy(e,t){let n={[By]:Vy,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${By}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Gy(e,t){let n=Wy(e.presets,t).root??jy;return{node:Fy(Ry(n,e.root)),path:zy(n)?`presets.${t}.root`:`root`}}function Ky(e,t){return{...e.globals,...Wy(e.presets,t).globals}}const qy=new Map;function Jy(e,t,n){qy.set(e,{permanent:!0,resolve:t,paletteOf:n})}Jy(`themes`,()=>Lh(),e=>by(e));const Yy=`placementThemes`;Jy(Yy,Rh,(e,t)=>xy(e,t.palette));for(let{name:e,members:t}of sv)Jy(e,()=>t);function Xy(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Cy(n.basePalette,e.styles[t])}],[`presets`,{members:Hy(e.presets)}]])}function Zy(e){return[...new Set([...qy.keys(),...e.keys()])]}function Qy(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=qy.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(eb(e,t))}const $y=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function eb(e,t){let n=$y.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Zy(t).join(`, `)})`}const tb=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*nb(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const rb=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,ib=RegExp(`^(?:(\\$)(?:\\.(${rb}))?|\\.(${rb})?)(?=[\\s)]|$)`);function ab(e,t,n){let r=ib.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const ob=/^(\w+)\b\s*([\s\S]*)$/;function*sb(e,t){let n=[t];for(let r of nb(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=ob.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:ab(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(ab(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const cb=/(?<![.$])\btemplate\s+$/;function*lb(e,t,n){let r=0;for(let i of[...e.matchAll(tb)]){let a=i.index+i[0].length;cb.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:ab(e.slice(a),t,n)}),r=a}}function*ub(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...sb(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...lb(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const db=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${rb})`,`g`);function*fb({code:e,dot:t,root:n}){let r=e.replace(tb,``);for(let e of[...r.matchAll(db)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function pb(e,t){let n=new Map;for(let r of ub(e,t))for(let e of fb(r))n.has(e)||n.set(e,r.via);return n}const mb=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,hb={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*gb(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(tb)]){let o=e.slice(t,a.index),s=mb.exec(o);if(s!==null)n=hb[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function _b(e,t){let n=new Map;for(let{code:r,via:i}of ub(e,t))for(let{name:e,site:t}of gb(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function vb(e,t){return new Set([...yb(e,t)].filter(e=>Object.hasOwn(t,e)))}function yb(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of ub(e,t))for(let{name:e}of lb(r,i,a))n.add(e);return n}function bb(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function xb(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),Sb(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function Sb(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&Og(e.parse)===`json`}function Cb(e){let t=s.basename(e),n=s.dirname(e);for(;;){let r=wb(n);if(r!==null)return{dir:r,name:t,leaf:n===s.dirname(e)};t=s.basename(n),n=s.dirname(n)}}function wb(e){try{return p.statSync(e).isDirectory()?p.realpathSync(e):null}catch{return null}}var Tb=Te((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Vt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Lt(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Rt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Ht,n=Ht){let r=new Gt(e);return t!==Ht&&(r.onBOL=new Set([t])),n!==Ht&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||tt(e)?e:Array.isArray(e)?cn.array(e,{name:n}):o(e)?cn.object(e,void 0,{name:n}):u(e)?cn.map(e,{name:n}):d(e)?cn.set(e,{name:n}):typeof e!=`function`||We(e)||Qe(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:ee,u:x}}function ee(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:We(n.value)?1:(Lt(r,t,te(e,this,t,n,!1)),2)}function x(e,t,n,r){let i=te(e,this,t,n);return e.l(t,i,r)}function S(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return ye(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return We(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(We(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function te(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:ye(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function ne(e,t){return{t:e,i:t,o:C,u:re}}function C(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!Qe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Qe(n.value)?1:(Lt(r,t,ae(e,0,0,n,!1,!1)),2)}function re(e,t,n,r){let i=ae(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ie(e,t,n){var r;let{name:i,addInitializer:a}=n;return Qe(t)||(t=Gn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function ae(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Qe(o)||(o=Gn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function w(e,t){return{t:e,i:t,o:T,u:oe}}function T(e,t,n){return this.u(e,t,n,!1)===null?0:1}function oe(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function E(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new M(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[A],n=this,i=e.j.get(a);i instanceof M&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[A],n=e.j.get(a);if(n instanceof M&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function se(e,t){return{t:e,i:t,o:ce,u:le}}function ce(e,t,n){return this.u(e,t,n,!1)===null?0:1}function le(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ue(e,t,n){function r(e,t){let n=Ct(e)[A];return(n.V??=new Map).set(o,()=>new vn(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[A]??r(this,t.get.call(this)))._(o)},set(e){return(this[A]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function de(e){return{t:Yt,i:e,o:fe,u:pe}}function fe(e,t,n,r){var i,a,o;if(n.get)return fn.o(e,t,n,r);if(n.set){let i=We(n.set)?n.set:ye(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(Lt(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?rn:cn;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function pe(e,t,n,r){var i;return n.get?fn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:ye(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?rn:cn).u(e,t,n,r))}function me(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function he(e){return e||Zt}function ge(e){return me(e,ue)}function _e(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function ve(e){return me(e,E)}function ye(e,t,n=!1,r){function i(){return be(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),gn&&(_n.value=e,Lt(i,`name`,_n)),i}function be(e,t,n,r,i){let a=xe(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{Se(a)}}function xe(e,t){let n=N.trackingDerivation,r=!t||!n;Pe();let i=N.allowStateChanges;r&&Oe();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:hn++,D:mn};return mn=a.B,a}function Se(e){mn!==e.B&&t(30),mn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Fe(),e.R&&ke(e.k),N.suppressReactionErrors=!1}function Ce(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function we(e){return e instanceof xn}function Te(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Oe(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return ke(t),!0}if(e.K===2)return ke(t),!0}}return Ae(e),ke(t),!1}}}function Ee(e,t,n){Ae(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&Me(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,je(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function De(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Me(t[n],e);e.K=-1}function D(e){let t=Oe();try{return e()}finally{ke(t)}}function Oe(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function ke(e){N.trackingDerivation=e}function Ae(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function je(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Me(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ne(e))}function Ne(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function Pe(){N.inBatch++}function Fe(){--N.inBatch===0&&(ze(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof M&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ie(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ie))}function Le(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ne(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Re(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function ze(){N.inBatch>0||N.isRunningReactions||On(Be)}function Be(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Ve(e){return me(e,S)}function He(e){return function(t,n){return n&&typeof n.kind==`string`?S(e?Pn:Mn,t,n):r(t)?ye(t.name||`<unnamed action>`,t,e):r(n)?ye(t,n,e):i(t)?Ve(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Ue(e){return be(0,!1,e,this,void 0)}function We(e){return r(e)&&!0===e.isMobxAction}function Ge(e,t=Bt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ke(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function Ke(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function qe(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Je(e,t,n,r){let i=Wt(t);return kt(()=>{let t=Ct(e,r)[A];Ut(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ye(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Ye)),t}function Xe(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),Xe)),t}function Ze(e){r(e.cancel)&&e.cancel()}function Qe(e){return!0===e?.isMobXFlow}function $e(e,t){var n;if(t===void 0)return bn(e);if(!1===Tt(e))return!1;let r=e[A];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Et(e,t)):!1}function et(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[A];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[A]||Kt(e)||kn(e)||bn(e)}function tt(e){return et(e)}function nt(e){return Tt(e)?e[A].nt():ir(e)||sr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function rt(e,n){return Tt(e)?e[A].et(n):ir(e)||sr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function it(e){if(Tt(e))return e[A].it();t(38)}function at(e,t,n){if(bn(e)){let r,i=!0;return Ge(()=>{let a=e.get();if(!i||n){let n=Oe();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),ke(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),mt(e,t)}function ot(e,t,n){return e.set(t,n),n}function st(e,t){if(typeof e!=`object`||!e||e instanceof Date||!tt(e))return e;if(yn(e)||bn(e))return st(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=ot(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=st(e,t)}),n}if(sr(e)){let n=ot(t,e,new Set);return e.forEach(e=>{n.add(st(e,t))}),n}if(ir(e)){let n=ot(t,e,new Map);return e.forEach((e,r)=>{n.set(r,st(e,t))}),n}{let n=ot(t,e,{});return it(e).forEach(r=>{Rt.propertyIsEnumerable.call(e,r)&&(n[r]=st(e[r],t))}),n}}function ct(e,t){Pe();try{return e.apply(t)}finally{Fe()}}function lt(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[A].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=ye(`When-effect`,t);var a=Ge(t=>{Ce(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ut(e){return e[A]}function dt(e){return e.st!==void 0&&e.st.length>0}function ft(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function O(e,n){let r=Oe();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{ke(r)}}function pt(e){return e.ot!==void 0&&e.ot.length>0}function mt(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function ht(e,t){let n=Oe(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);ke(n)}}function gt(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==Rt;){let t=It(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function k(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function _t(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[A];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function bt(e){return a(e)&&er(e[A])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,A))return e;let n=t?.name??`ObservableObject`;return c(e,A,new ur(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return j[r]??(j[r]=de({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return cr[e]||(cr[e]={get(){return this[A]._(e)},set(t){return this[A].M(e,t)}})}function Tt(e){return!!a(e)&&dr(e[A])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[A].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[A],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Kt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[A]))return e[A];t(28)}function Dt(e,n){return e||t(29),n===void 0?Kt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[A]?e[A]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(We(e))return e.name;n=Tt(e)||ir(e)||sr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=Oe();Pe();try{return e()}finally{Fe(),ke(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=fr.call(e);if(s!==fr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=Mt(e),t=Mt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!jt(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(pr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,It=Object.getOwnPropertyDescriptor,Lt=Object.defineProperty,Rt=Object.prototype,zt=[];Object.freeze(zt);let Bt={};Object.freeze(Bt);let Vt=Object.toString(),Ht=()=>{},Ut=Reflect.ownKeys,Wt=Object.getOwnPropertyDescriptors,A=Symbol(`mobx administration`);var Gt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Le(this)}reportChanged(){Pe(),Re(this),Fe()}toString(){return this.tt}};let Kt=l(`Atom`,Gt),qt=Object.is,Jt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Yt=`true`,Xt=de(),j=[Xt],Zt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Zt);let Qt=se(`observable`),$t=se(`observable.ref`,{A:y}),en=se(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ir(e)||sr(e)?e:Array.isArray(e)?cn.array(e,{name:n,deep:!1}):o(e)?cn.object(e,void 0,{name:n,deep:!1}):u(e)?cn.map(e,{name:n,deep:!1}):d(e)?cn.set(e,{name:n,deep:!1}):void 0}}),tn=se(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),nn={box(e,t){let n=he(t);return new vn(e,_e(n),n.name,!0,n.equals)},array(e,t){let n=he(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new Qn(n,t,r);Lt(i.j,A,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,_e(n),n.name)},map(e,t){let n=he(t);return new rr(e,_e(n),n.name)},set(e,t){let n=he(t);return new or(e,_e(n),n.name)},object:(e,t,n)=>kt(()=>Je(function(e,t){var n;return(n=(e=Ct(e,t))[A]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},rn=ge($t),an=ge(en),on=ge(Qt),sn=ge(tn);var cn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ue(Qt,e,t):tt(e)?e:o(e)?cn.object(e,t,n):Array.isArray(e)?cn.array(e,t):u(e)?cn.map(e,t):d(e)?cn.set(e,t):typeof e==`object`&&e?e:cn.box(e,t)},Qt,nn);let ln=`computed`,un=w(ln),dn=ve(w(`computed.struct`,{equals:_})),fn=function(e,t){if(t&&typeof t.kind==`string`)return E(un,e,t);if(o(e))return ve(w(ln,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new M(n)};var pn;Ft(fn,un);let mn=0,hn=1,gn=(pn=It(()=>{},`name`)?.configurable)!=null&&pn,_n={value:`action`,configurable:!0,writable:!1,enumerable:!1};var vn=class extends Gt{constructor(e,t,n=`ObservableValue`,r=!0,i=qt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(dt(this)){let t=O(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),pt(this)&&ht(this,{type:Xn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let yn=l(`ObservableValue`,vn);var M=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new xn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=ye(`ComputedValue-setter`,e.set)),this.xt=e.equals||qt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Le(this),Te(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ie)}else Te(this)&&(this.Nt(),Pe(),this.rt=this.Rt(!1),Fe());let e=this.rt;if(we(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||we(e)||we(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Ee(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(De(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,M);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),ze())}X(){if(!this.isDisposed){Pe(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,Te(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Fe()}}track(e){if(this.isDisposed)return;Pe(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Ee(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&De(this),we(n)&&this.Pt(n.cause),Fe()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Pe(),De(this),Fe()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=He(!1);Ft(In,Mn);let Ln=He(!0);Ft(Ln,Pn);let Rn=Ve(Nn),zn=Ve(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=ne(`flow`),Wn=ne(`flow.bound`,{bound:!0}),Gn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return ie(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=In(i,function(){try{o&&Ze(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ht,Ht),Ze(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=me(Wn,ie),qn={has:(e,t)=>ut(e).et(t),get:(e,t)=>ut(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ut(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ut(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ut(e).l(t,n))==null||r},ownKeys:e=>ut(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[A];return t===A?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[A];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Gt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=zt),dt(this)){let r=O(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return zt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&ht(this,i)}Ft(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&ht(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(dt(this)){let n=O(this,{type:Xn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[A];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[A].wt(e,t,n)},push(...e){let t=this[A];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[A].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};k(`at`,_t),k(`concat`,_t),k(`flat`,_t),k(`includes`,_t),k(`indexOf`,_t),k(`join`,_t),k(`lastIndexOf`,_t),k(`slice`,_t),k(`toString`,_t),k(`toLocaleString`,_t),k(`toSorted`,_t),k(`toSpliced`,_t),k(`with`,_t),k(`every`,vt),k(`filter`,vt),k(`find`,vt),k(`findIndex`,vt),k(`findLast`,vt),k(`findLastIndex`,vt),k(`flatMap`,vt),k(`forEach`,vt),k(`map`,vt),k(`some`,vt),k(`toReversed`,vt),k(`reduce`,yt),k(`reduceRight`,yt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[A]=tr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,kt(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new vn(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(dt(this)){let r=O(this,{type:n?Xn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=pt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ct(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}}Jt(e,t){ct(()=>{var n;let r=new vn(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=pt(this);n&&ht(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return xt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return xt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ir(e)&&(e=new Map(e)),ct(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Rt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){ct(()=>{D(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ct(()=>{let n=function(e){if(u(e)||ir(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[A]=ar,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ct(()=>{D(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(dt(this)){let t=O(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ct(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=pt(this);t&&ht(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=pt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return ct(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return St({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ct(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Xt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Gt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof M)return n.set(t),!0;if(dt(this)){let n=O(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}return!0}Tt(e){return N.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new vn(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Lt(this.h,e,t);this.Yt(e,t.value)}finally{Fe()}return!0}S(e,t,n,r=!1){try{Pe();let i=this.Dt(e);if(!i)return i;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Lt(this.h,e,o);let s=new vn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Fe()}return!0}m(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=wt(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Lt(this.h,e,a);this.j.set(e,new M(t)),this.Yt(e,void 0)}finally{Fe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;Pe();let r=pt(this),i=this.j.get(e),a;if(i||!r||(a=It(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof vn&&(a=i.rt),Re(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&ht(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Fe()}return!0}Yt(e,t){var n;let r=pt(this);r&&r&&ht(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Ut(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Rt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=A,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=Ce,e._allowStateChangesInsideComputed=Ue,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=Se,e._getAdministration=Dt,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||bt(e)||yn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=xe,e.action=In,e.actionBound=Rn,e.autorun=Ge,e.compareDefault=qt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=fn,e.computedStruct=dn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[A].l(n,r);t(39)},e.entries=function(e){return Tt(e)?nt(e).map(t=>[t,e[t]]):ir(e)?nt(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Je,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(rt(e,n))return Tt(e)?e[A].Tt(n):ir(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return Ye(Et(e,t))},e.getObserverTree=function(e,t){return Xe(Et(e,t))},e.has=rt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ft(Dt(e,t),n)}(e,t,n):function(e,t){return ft(Dt(e),t)}(e,t)},e.isAction=We,e.isBoxedObservable=yn,e.isComputed=function(e){return $e(e)},e.isComputedProp=function(e,t){return $e(e,t)},e.isFlow=Qe,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=tt,e.isObservableArray=bt,e.isObservableMap=ir,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return et(e,t)},e.isObservableSet=sr,e.keys=nt,e.makeAutoObservable=function(e,t,n){return o(e)?Je(e,e,t,n):(kt(()=>{let r=Ct(e,n)[A];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ut(e),...Ut(t)]);n.delete(`constructor`),n.delete(A),c(t,Jn,n)}e[Jn].forEach(e=>gt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[A];Ut(t).forEach(e=>gt(r,e,t[e]))}),e},e.observable=cn,e.observableDeep=on,e.observableRef=rn,e.observableShallow=an,e.observableStruct=sn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return at(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ir(e)&&!sr(e)&&!Tt(e))return at(r,t,n);return mt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return qe(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return qe(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=Jt,e.ownKeys=it,e.reaction=function(e,t,n=Bt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=Ce(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=In(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=Ke(n),d,f=!0,p=!1,m=n.equals||qt,h=new En(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Tt(e)?e[A].Dt(n):ir(e)||sr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ue,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){Pe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Fe()}return}Tt(n)?n[A].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Pe(),r>=n.length&&(n.length=r+1),n[r]=i,Fe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return st(e,new Map)},e.transaction=ct,e.untracked=D,e.values=function(e){return Tt(e)?nt(e).map(t=>e[t]):ir(e)?nt(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):bt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=lt(e,n,Ft({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):lt(e,t,n||{})}})),Eb=Te((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++j.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=ie(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function ee(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function x(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function S(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function te(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let ne=Reflect.ownKeys;function C(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function re(e){return e===null?null:typeof e==`object`?``+e:e}function ie(e,t){return o.hasOwnProperty.call(e,t)}let ae=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function T(e,t,n){return n?e|=t:e&=~t,e}function oe(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let E=Symbol(`mobx administration`);var se=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return w(this.flags_,1)}set isBeingObserved(e){this.flags_=T(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=T(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=T(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return un(this)}reportChanged(){on(),dn(this),sn()}toString(){return this.name_}};let ce=b(`Atom`,se);function le(e,t=f,n=f){let r=new se(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ue(e,t){return e===t}function de(e,t){return Li(e,t)}function fe(e,t){return Li(e,t,1)}let pe=Object.is;function me(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?O.array(e,{name:n}):g(e)?O.object(e,void 0,{name:n}):ee(e)?O.map(e,{name:n}):S(e)?O.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function he(e,t,r){if(e==null||ki(e)||fi(e)||gi(e)||xi(e))return e;if(Array.isArray(e))return O.array(e,{name:r,deep:!1});if(g(e))return O.object(e,void 0,{name:r,deep:!1});if(ee(e))return O.map(e,{name:r,deep:!1});if(S(e))return O.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function ge(e){return e}function _e(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ve=`override`,ye={annotationType_:ve,make_:xe,extend_:Se};function be(e){return e.annotationType_===ve}function xe(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ie(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function Se(e,t,r,i){n(44,this.annotationType_)}function Ce(e,t){return{annotationType_:e,options_:t,make_:we,extend_:Te}}function we(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:zn(n.value)?1:(a(r,t,D(e,this,t,n,!1)),2)}function Te(e,t,n,r){let i=D(e,this,t,n);return e.defineProperty_(t,i,r)}function Ee(e,t,r){oe(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function De(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function D(e,t,n,r,i=j.safeDescriptors){var a,o;De(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Oe(e,t){return{annotationType_:e,options_:t,make_:ke,extend_:Ae}}function ke(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!ie(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ne(e,this,t,n,!1,!1)),2)}function Ae(e,t,n,r){let i=Ne(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function je(e,t,n){var r;oe(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function Me(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Ne(e,t,n,r,i,a=j.safeDescriptors){Me(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Pe(e,t){return{annotationType_:e,options_:t,make_:Fe,extend_:Ie}}function Fe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ie(e,t,n,i){return Re(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Le(e,t,n){oe(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new At(o)}return o(function(){let e=Ei(this)[E],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[E],n=e.values_.get(a);if(n instanceof At&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function Re(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function ze(e,t){return{annotationType_:e,options_:t,make_:Be,extend_:Ve}}function Be(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ve(e,t,n,r){return Ue(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??me,r)}function He(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);oe(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Ei(e)[E];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??me,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[E]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[E]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ue(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let We=Ge();function Ge(e){return{annotationType_:`true`,options_:e,make_:Je,extend_:Ye}}let Ke=[We];function qe(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ke[r]??(Ke[r]=Ge({deep:t,autoBind:n}))}function Je(e,t,n,r){var i;if(n.get)return k.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?lt:O;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ye(e,t,n,r){var i;return n.get?k.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:xt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?lt:O).extend_(e,t,n,r))}function Xe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Ze={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ze);function Qe(e){return e||Ze}let $e=ze(`observable`),et=ze(`observable.ref`,{enhancer_:ge}),tt=ze(`observable.shallow`,{enhancer_:he}),nt=ze(`observable.struct`,{enhancer_:_e});function rt(e){return Xe(e,He)}function it(e){return e.deep===!0?me:e.deep===!1?ge:ot(e.defaultDecorator)}function at(e){return e?e.defaultDecorator??qe(e):void 0}function ot(e){return e?e.options_?.enhancer_??me:me}function st(e,t,n){return t&&typeof t.kind==`string`?He($e,e,t):xr(e)?e:g(e)?O.object(e,t,n):Array.isArray(e)?O.array(e,t):ee(e)?O.map(e,t):S(e)?O.set(e,t):typeof e==`object`&&e?e:O.box(e,t)}let ct={box(e,t){let n=Qe(t);return new Ot(e,it(n),n.name,!0,n.equals)},array(e,t){let n=Qe(t);return ai(e,it(n),n.name)},map(e,t){let n=Qe(t);return new hi(e,it(n),n.name)},set(e,t){let n=Qe(t);return new bi(e,it(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},lt=rt(et),ut=rt(tt),dt=rt($e),ft=rt(nt);var O=r(st,$e,ct);let pt=`computed`;function mt(e){return Xe(e,Le)}let ht=Pe(pt),gt=mt(Pe(`computed.struct`,{equals:de})),k=function(e,t){if(t&&typeof t.kind==`string`)return Le(ht,e,t);if(g(e))return mt(Pe(pt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new At(r)};r(k,ht);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=j.trackingDerivation,c=!t||!o;on();let l=j.allowStateChanges;c&&(Ut(),l=Et(!0));let u=j.allowStateReads;A(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(j.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Gt(e.prevAllowStateReads_),sn(),e.runAsAction_&&Wt(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),j.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}function Dt(e){j.allowStateChanges=e}var Ot=class extends se{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=pe){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&bn()&&xn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==j.UNCHANGED){let n=bn();n&&Sn({type:ni,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(It(this),Kr(this)){let t=P(this,{object:this,type:ni,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?j.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Jr(this)&&Xr(this,{type:ni,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new Mt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||pe,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){pn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return w(this.flags_,1)}set isComputing(e){this.flags_=T(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=T(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=T(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),j.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),on(),this.value_=this.computeValue_(!1),sn());else{let e=this.isBeingObserved;if(un(this),Pt(this)){let e=j.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(j.trackingContext=this),this.trackAndCompute()&&fn(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(ln)}let e=this.value_;if(Nt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Rt(this,this.derivation,this.scope_);else if(j.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Vt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:j.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=A(!0),n=Ut(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(j.disableErrorBoundaries)i.get();else try{i.get()}catch{return Wt(n),Gt(t),!0}if(e.dependenciesState_===2)return Wt(n),Gt(t),!0}}return Kt(e),Wt(n),Gt(t),!1}}}function Ft(){return j.trackingDerivation!==null}function It(e){let t=!!e.observers_&&e.observers_.size>0;!j.allowStateChanges&&(t||j.enforceActions===`always`)&&console.warn(`[MobX] `+(j.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function Lt(e){!j.allowStateReads&&j.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Rt(e,t,n){let r=A(!0);Kt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++j.runId;let i=j.trackingDerivation;j.trackingDerivation=e,j.inBatch++;let a;if(j.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return j.inBatch--,j.trackingDerivation=i,Bt(e),zt(e),Gt(r),a}function zt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:j.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Bt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&rn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,nn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Vt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)rn(t[n],e);e.dependenciesState_=-1}function Ht(e){let t=Ut();try{return e()}finally{Wt(t)}}function Ut(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function Wt(e){j.trackingDerivation=e}function A(e){let t=j.allowStateReads;return j.allowStateReads=e,t}function Gt(e){j.allowStateReads=e}function Kt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let qt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Jt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Yt=!0,Xt=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Yt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Yt=!1),Yt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Jt):(setTimeout(()=>{Xt||n(35)},1),new Jt)}();function Zt(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&n(36),Xt=!0,Yt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Jt}}function Qt(){return j}function $t(){let e=new Jt;for(let t in e)qt.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions}function en(e){return!!e.observers_&&e.observers_.size>0}function tn(e){return e.observers_??new Set}function nn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&an(e))}function an(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function on(){j.inBatch++}function sn(){--j.inBatch===0&&(_n(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&cn())}function cn(){j.isRunningUnobservations=!0;try{let e=j.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof At&&n.suspend_())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}function ln(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(ln))}function un(e){Lt(e);let t=j.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&j.inBatch>0&&an(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function dn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function fn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function pn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var mn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return w(this.flags_,1)}set isDisposed(e){this.flags_=T(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=T(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=T(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),_n())}runReaction_(){if(!this.isDisposed){on(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}j.trackingContext=e,sn()}}track(e){if(this.isDisposed)return;on();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=j.trackingContext;j.trackingContext=this;let i=Rt(this,e,void 0);j.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Vt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),sn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(j.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;j.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(on(),Vt(this),sn())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[E]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function hn(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}}let gn=e=>e();function _n(){j.inBatch>0||j.isRunningReactions||gn(vn)}function vn(){j.isRunningReactions=!0;let e=j.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}j.isRunningReactions=!1}let yn=b(`Reaction`,mn);function M(e){let t=gn;gn=n=>e(()=>t(n))}function bn(){return!!j.spyListeners.length}function xn(e){if(!j.spyListeners.length)return;let t=j.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return j.spyListeners.push(e),d(()=>{j.spyListeners=j.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=Ce(N),kn=Ce(`action.bound`,{bound:!0}),An=Ce(En,{autoAction:!0}),jn=Ce(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return Xe(e,Ee)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Ee(e?An:On,t,r);if(p(t))return xt(t.name||Dn,t,e);if(p(r))return xt(t,r,e);if(m(t))return Mn(Ce(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return St(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new mn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new mn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||pe,_=new mn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=Tt(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?Mi(t,n):Mi(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Zt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;j.enforceActions=e,j.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,j.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&M(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),gi(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=ae(t);return Fi(()=>{let t=Ei(e,i)[E];ne(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Mi(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Mi(e,t))}function er(e){let t={name:e.name_};return en(e)&&(t.observers=Array.from(tn(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return Xe(e,je)}let or=Oe(`flow`),sr=Oe(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return je(or,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++nr,a=Pn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(gi(e)||fi(e)||kt(e))i=Ni(e);else if(ki(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return jt(e);if(ki(e)===!1)return!1;let r=e[E];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Mi(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(gi(e)||fi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(ki(e)){var r,i;let n=e[E];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return ki(e)||!!e[E]||ce(e)||yn(e)||jt(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(ki(e))return e[E].keys_();if(gi(e)||xi(e))return Array.from(e.keys());if(fi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(ki(e))return Cr(e).map(t=>e[t]);if(gi(e))return Cr(e).map(t=>e.get(t));if(xi(e))return Array.from(e.values());if(fi(e))return e.slice();n(6)}function Tr(e){if(ki(e))return Cr(e).map(t=>[t,e[t]]);if(gi(e))return Cr(e).map(t=>[t,e.get(t)]);if(xi(e))return Array.from(e.entries());if(fi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!xi(e)){on();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{sn()}return}ki(e)?e[E].set_(t,r):gi(e)?e.set(t,r):xi(e)?e.add(t):fi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),on(),t>=e.length&&(e.length=t+1),e[t]=r,sn()):n(8)}function Dr(e,t){ki(e)?e[E].delete_(t):gi(e)||xi(e)?e.delete(t):fi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(ki(e))return e[E].has_(t);if(gi(e)||xi(e))return e.has(t);if(fi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(ki(e))return e[E].get_(t);if(gi(e))return e.get(t);if(fi(e))return e[t];n(11)}}function Ar(e,t,r){if(ki(e))return e[E].defineProperty_(t,r);n(39)}function jr(e){if(ki(e))return e[E].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=Ni(e);if(fi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(gi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(xi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(ki(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Yr(i,t)}function Pr(e,t,n,r){return Fr(Ni(e,t),n,r)}function Fr(e,t,n){if(jt(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ut();t({observableKind:`computed`,debugObjectName:e.name_,type:ni,object:e,newValue:a,oldValue:i}),Wt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ni,newValue:e.value_,oldValue:void 0}),Yr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(kt(e)||jt(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(fi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(xi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(gi(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){on();try{return e.apply(t)}finally{sn()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[E].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Bn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Vr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Ur(e){return e[E]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=Ei(e,t),(n=e[E]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function P(e,t){let r=Ut();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Wt(r)}}function Jr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Yr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Xr(e,t){let n=Ut(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Wt(n)}}function Zr(e,t,n){return Fi(()=>{let r=Ei(e,n)[E];ne(t).forEach(e=>ei(r,e,t[e]))}),e}let Qr=Symbol(`mobx-keys`);function $r(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Ei(e,r)[E];if(!e[Qr]){let t=Object.getPrototypeOf(e),n=new Set([...ne(e),...ne(t)]);n.delete(`constructor`),n.delete(E),v(t,Qr,n)}e[Qr].forEach(e=>ei(n,e,t&&e in t?t[e]:!0))}),e)}function ei(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;ji(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}Ai(e,r,t)}let ti=`splice`,ni=`update`,ri={get(e,t){let n=e[E];return t===E?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ie(oi,t)?oi[t]:e[t]},set(e,t,n){let r=e[E];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ii=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new se(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){It(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=P(this,{object:this.proxy_,type:ti,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Jr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ni,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Xr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Jr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ti,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Xr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){It(this.atom_);let r=n[e];if(Kr(this)){let n=P(this,{type:ni,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function ai(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ii(n,t,r);y(i.values_,E,i);let a=new Proxy(i.values_,ri);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var oi={clear(){return this.splice(0)},replace(e){let t=this[E];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[E];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[E].spliceWithArray_(e,t,n)},push(...e){let t=this[E];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[E].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[E];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return j.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[E],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};si(`at`,ci),si(`concat`,ci),si(`flat`,ci),si(`includes`,ci),si(`indexOf`,ci),si(`join`,ci),si(`lastIndexOf`,ci),si(`slice`,ci),si(`toString`,ci),si(`toLocaleString`,ci),si(`toSorted`,ci),si(`toSpliced`,ci),si(`with`,ci),si(`every`,li),si(`filter`,li),si(`find`,li),si(`findIndex`,li),si(`findLast`,li),si(`findLastIndex`,li),si(`flatMap`,li),si(`forEach`,li),si(`map`,li),si(`some`,li),si(`toReversed`,li),si(`reduce`,ui),si(`reduceRight`,ui);function si(e,t){typeof Array.prototype[e]==`function`&&(oi[e]=t(e))}function ci(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function li(e){return function(t,n){let r=this[E];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function ui(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let di=b(`ObservableArrayAdministration`,ii);function fi(e){return h(e)&&di(e[E])}let pi={},mi=`delete`;var hi=class{constructor(e,t=me,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[E]=pi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=le(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!j.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),ge,`${this.name_}.${C(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(Kr(this)){let r=P(this,{type:n?ni:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(It(this.keysAtom_),Kr(this)&&!P(this,{type:mi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Jr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:mi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Xr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=bn(),i=Jr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ni,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Xr(this,a),r&&wn()}}addValue_(e,t){It(this.keysAtom_),zr(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${C(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Jr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Xr(this,i),n&&wn()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return gi(e)&&(e=new Map(e)),zr(()=>{g(e)?te(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):ee(e)?(x(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Ht(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=vi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},gi=b(`ObservableMap`,hi);function _i(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function vi(e){if(ee(e)||gi(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let yi={};var bi=class{constructor(e,t=me,n=`ObservableSet@`+u()){this.name_=void 0,this[E]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=le(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Ht(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(It(this.atom_),Kr(this)){let t=P(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Jr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Xr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!P(this,{type:mi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Jr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:mi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Xr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return Si({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Si({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return xi(e)&&(e=new Set(e)),Array.isArray(e)||S(e)?zr(()=>{let t=S(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},xi=b(`ObservableSet`,bi);function Si(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let Ci=Object.create(null),wi=`remove`;var Ti=class{constructor(e,t=new Map,r,i=We){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new se(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof At)return n.set(t),!0;if(Kr(this)){let n=P(this,{type:ni,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=Jr(this),i=bn(),a=r||i?{type:ni,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Xr(this,a),i&&wn()}return!0}get_(e){return j.trackingDerivation&&!ie(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ie(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!j.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,ge,`${this.name_}.${C(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);ji(this,n,e);let i=n.extend_(this,e,t,r);return i&&Ai(this,n,e),i}defineProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{sn()}return!0}defineObservableProperty_(e,t,n,r=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Oi(e),s={configurable:j.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{sn()}return!0}defineComputedProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!P(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=Oi(e),o={configurable:j.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new At(t)),this.notifyPropertyAddition_(e,void 0)}finally{sn()}return!0}delete_(e,t=!1){if(It(this.keysAtom_),!ie(this.target_,e))return!0;if(Kr(this)&&!P(this,{object:this.proxy_||this.target_,name:e,type:wi}))return null;try{var n;on();let r=Jr(this),a=bn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof Ot&&(s=o.value_),dn(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:wi,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Xr(this,t),a&&wn()}}finally{sn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Jr(this),i=bn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&Sn(n),r&&Xr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),ne(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Ei(e,t){if(t&&ki(e)&&n(`Options can't be provided for already observable objects.`),ie(e,E))return Ni(e)instanceof Ti||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,E,new Ti(e,new Map,String(r),at(t))),e}let Di=b(`ObservableObjectAdministration`,Ti);function Oi(e){return Ci[e]||(Ci[e]={get(){return this[E].getObservablePropValue_(e)},set(t){return this[E].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[E]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!be(t)&&ie(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Mi(e,t){if(typeof e==`object`&&e){if(fi(e))return t!==void 0&&n(23),e[E].atom_;if(xi(e))return e.atom_;if(gi(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(ki(e)){if(!t)return n(26);let r=e[E],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ce(e)||jt(e)||yn(e))return e}else if(p(e)&&yn(e[E]))return e[E];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(ce(e)||jt(e)||yn(e)||gi(e)||xi(e))return e;if(e[E])return e[E];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=Mi(e,t);else if(zn(e))return e.name;else n=ki(e)||gi(e)||xi(e)?Ni(e):Mi(e);return n.name_}function Fi(e){let t=Ut(),n=Et(!0);on();try{return e()}finally{sn(),Dt(n),Wt(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(ie(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return fi(e)?e.slice():ee(e)||gi(e)||S(e)||xi(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:E}),e.$mobx=E,e.FlowCancellationError=rr,e.ObservableMap=hi,e.ObservableSet=bi,e.Reaction=mn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Gt,e._allowStateReadsStart=A,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=wt,e._getAdministration=Ni,e._getGlobalState=Qt,e._interceptReads=pr,e._isComputingDerivation=Ft,e._resetGlobalState=$t,e._startAction=Ct,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=pe,e.compareIdentity=ue,e.compareShallow=fe,e.compareStructural=de,e.computed=k,e.computedStruct=gt,e.configure=Yn,e.createAtom=le,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Mi,e.getDebugName=Pi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=kt,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=fi,e.isObservableMap=gi,e.isObservableObject=ki,e.isObservableProp=Sr,e.isObservableSet=xi,e.keys=Cr,e.makeAutoObservable=$r,e.makeObservable=Zr,e.observable=O,e.observableDeep=dt,e.observableRef=lt,e.observableShallow=ut,e.observableStruct=ft,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=hn,e.override=ye,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Ht,e.values=wr,e.when=Br})),Db=Te(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Tb():t.exports=Eb()}))();function Ob(e){if(Array.isArray(e))return Object.freeze(e.map(Ob));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Ob(r);return Object.freeze(t)}return e}function kb(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function Ab(e){return typeof e==`string`?e:String(e)}function jb(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function Mb(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var Nb=class extends Error{constructor(e,t){super(t),this.variable=e}};function Pb(e){return e instanceof Nb||e instanceof Error&&e.cause!==void 0&&Pb(e.cause)}var Fb=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Wb(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Ib=class extends Fb{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Lb=class extends Fb{name=`EvalError`;kind=`EvalError`},Rb=class extends Lb{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Gb(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},zb=class extends Lb{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},Bb=class extends Lb{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},Vb=class extends Bb{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},Hb=class extends Lb{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Ub=class extends Lb{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Wb(e,t){let n=e.split(`
|
|
61
61
|
`),r=t.line-1,i=[];if(r-1>=0&&r-1<n.length&&i.push({num:r,text:n[r-1]??``}),r>=0&&r<n.length&&i.push({num:r+1,text:n[r]??``}),r+1<n.length&&i.push({num:r+2,text:n[r+1]??``}),i.length===0)return``;let a=String(i[i.length-1]?.num??1).length,o=[];for(let e of i)if(o.push(` ${String(e.num).padStart(a,` `)} | ${e.text}`),e.num===t.line){let e=` ${` `.repeat(a)} | `,n=` `.repeat(Math.max(0,t.column-1));o.push(`${e}${n}^`)}return o.join(`
|
|
62
|
-
`)}function
|
|
62
|
+
`)}function Gb(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Kb(e,t)})).sort((e,t)=>e.dist-t.dist),r=Math.max(2,Math.floor(e.length/2));return n.filter(e=>e.dist<=r).slice(0,3).map(e=>e.name)}function Kb(e,t){if(e===t)return 0;let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min((a[n-1]??0)+1,(i[n]??0)+1,(i[n-1]??0)+r)}for(let e=0;e<=r;e++)i[e]=a[e]??0}return i[r]??0}function qb(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Jb=new Map([[`if`,`If`],[`else`,`Else`],[`end`,`End`],[`range`,`Range`],[`with`,`With`],[`break`,`Break`],[`continue`,`Continue`],[`define`,`Define`],[`template`,`Template`],[`block`,`Block`],[`true`,`Bool`],[`false`,`Bool`],[`nil`,`Nil`]]),Yb={left:`{{`,right:`}}`};var Xb=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Yb){this.src=e,this.leftDelim=t.left,this.rightDelim=t.right}pos(){return{line:this.line,column:this.column,offset:this.offset}}err(e,t,n={}){return new Ib(e,t,{...n,source:this.src})}next(){if(this.pending){let e=this.pending;return this.pending=void 0,e}return this.read()}peek(){return this.pending||=this.read(),this.pending}read(){switch(this.mode){case`text`:return this.readText();case`action`:return this.readAction();case`done`:return this.makeToken(`EOF`,``,this.pos())}}readText(){if(this.offset>=this.src.length)return this.mode=`done`,this.makeToken(`EOF`,``,this.pos());let e=this.pos(),t=this.offset;for(;t<this.src.length&&!this.src.startsWith(this.leftDelim,t);)t+=1;let n=t<this.src.length&&this.src[t+this.leftDelim.length]===`-`,r=t;if(n)for(;r>this.offset&&Zb(this.src[r-1]??``);)--r;if(r>this.offset){let t=this.src.slice(this.offset,r);return this.advanceTo(r),this.makeToken(`Text`,t,e)}return this.advanceTo(t),this.emitLeftDelim(n)}emitLeftDelim(e){let t=this.pos();if(this.advanceBy(this.leftDelim.length),e)for(this.advanceBy(1);Zb(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`action`,this.src.startsWith(`/*`,this.offset)?this.readComment(t,e):this.makeToken(`LeftDelim`,e?`${this.leftDelim}-`:this.leftDelim,t,e?{trimLeft:!0}:{})}readComment(e,t){this.advanceBy(2);let n=this.offset,r=this.src.indexOf(`*/`,this.offset);if(r===-1)throw this.err(`unclosed comment`,e,{expected:`*/${this.rightDelim}`,found:`end of input`});this.advanceTo(r);let i=this.src.slice(n,r).trim();for(this.advanceBy(2);Zb(this.src[this.offset]??``);)this.advanceBy(1);let a=!1;if(this.src[this.offset]===`-`&&(a=!0,this.advanceBy(1)),!this.src.startsWith(this.rightDelim,this.offset))throw this.err(`expected \`${this.rightDelim}\` to close comment`,this.pos(),{expected:this.rightDelim,found:this.src[this.offset]??`end of input`});if(this.advanceBy(this.rightDelim.length),a)for(;Zb(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`text`,this.makeToken(`Comment`,i,e,{...t?{trimLeft:!0}:{},...a?{trimRight:!0}:{}})}readAction(){if(this.skipActionSpaces(),this.src.startsWith(`-${this.rightDelim}`,this.offset)){let e=this.pos();for(this.advanceBy(1+this.rightDelim.length),this.mode=`text`;Zb(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`RightDelim`,`-${this.rightDelim}`,e,{trimRight:!0})}if(this.src.startsWith(this.rightDelim,this.offset)){let e=this.pos();return this.advanceBy(this.rightDelim.length),this.mode=`text`,this.makeToken(`RightDelim`,this.rightDelim,e)}if(this.offset>=this.src.length)throw this.err(`unclosed action`,this.pos(),{expected:this.rightDelim,found:`end of input`});let e=this.src[this.offset],t=this.pos();switch(e){case`(`:return this.advanceBy(1),this.makeToken(`LeftParen`,`(`,t);case`)`:return this.advanceBy(1),this.makeToken(`RightParen`,`)`,t);case`|`:return this.advanceBy(1),this.makeToken(`Pipe`,`|`,t);case`,`:return this.advanceBy(1),this.makeToken(`Comma`,`,`,t);case`:`:if(this.src[this.offset+1]===`=`)return this.advanceBy(2),this.makeToken(`Declare`,`:=`,t);throw this.err("expected `:=`",t,{expected:`:=`,found:`:`});case`=`:return this.advanceBy(1),this.makeToken(`Assign`,`=`,t);case`"`:return this.readQuotedString(t);case"`":return this.readRawString(t);case`'`:return this.readChar(t)}if(e===`$`)return this.readVariable(t);if(e!==void 0&&($b(e)||Qb(e)&&$b(this.src[this.offset+1]??``)||e===`.`&&$b(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&ix(e))return this.readIdentifier(t);throw this.err(`unexpected character ${JSON.stringify(e)}`,t,{found:e??`end of input`})}readQuotedString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
|
|
63
63
|
`)throw this.err(`newline in interpreted string`,e,{found:`\\n`});if(n===`"`)return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated string literal`,e,{expected:`"`,found:`end of input`})}readRawString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){if(this.src[this.offset]==="`")return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated raw string literal`,e,{expected:"`",found:`end of input`})}readChar(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
|
|
64
|
-
`)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(
|
|
64
|
+
`)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(Qb(this.src[this.offset]??``)&&this.advanceBy(1),this.src[this.offset]===`0`&&this.offset+1<this.src.length){let n=this.src[this.offset+1];if(n===`x`||n===`X`){for(this.advanceBy(2);ex(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`||this.src[this.offset]===`p`||this.src[this.offset]===`P`)for(;this.isHexFloatTail(this.src[this.offset]??``);)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`o`||n===`O`){for(this.advanceBy(2);tx(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`b`||n===`B`){for(this.advanceBy(2);nx(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;$b(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);$b(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`e`||this.src[this.offset]===`E`)for(this.advanceBy(1),Qb(this.src[this.offset]??``)&&this.advanceBy(1);$b(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return ex(e)||e===`.`||e===`p`||e===`P`||e===`+`||e===`-`||e===`_`}finishNumber(e,t){if(this.offset===e)throw this.err(`expected number`,t,{expected:`digit`});return this.makeToken(`Number`,this.src.slice(e,this.offset),t)}readVariable(e){let t=this.offset;for(this.advanceBy(1);ax(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&ix(this.src[this.offset+1]??``);)for(this.advanceBy(1);ax(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Variable`,this.src.slice(t,this.offset),e)}readDotOrField(e){let t=this.offset;if(this.advanceBy(1),!ix(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;ax(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&ix(this.src[this.offset+1]??``);)for(this.advanceBy(1);ax(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Field`,this.src.slice(t,this.offset),e)}readIdentifier(e){let t=this.offset;for(;ax(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Jb.get(n);return r?this.makeToken(r,n,e):this.makeToken(`Identifier`,n,e)}skipActionSpaces(){for(;this.offset<this.src.length;){let e=this.src[this.offset];if(e===` `||e===` `||e===`\r`||e===`
|
|
65
65
|
`)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
|
|
66
|
-
`?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function
|
|
67
|
-
`}function
|
|
68
|
-
`;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new Ab(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function _x(e,t,n){let r=gx(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Ab(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function vx(e,t){if(t(e)!==!1)for(let n of yx(e))vx(n,t)}function yx(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return Vb(e)}}const bx=Symbol(`go-template-js.MISSING`);function xx(e,t){if(e==null)return bx;if(e instanceof Map)return e.has(t)?e.get(t):bx;if(Array.isArray(e))return bx;if(typeof e==`object`){let n=e;return t in n?n[t]:bx}return bx}function Sx(e,t){let n=e;for(let e of t){if(n===bx)return bx;n=xx(n,e)}return n}function Cx(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>Cx(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Cx(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>Cx(e[n],t[n])):!1}return!1}const wx=new WeakSet;function Tx(e){return wx.add(e),e}function Ex(e){return wx.has(e)}function Dx(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function Ox(e,t){return{eq:{fn:(e,...t)=>t.some(t=>jx(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!jx(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Mx(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Mx(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Mx(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Mx(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Nx(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Px(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Ix(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>zx(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${zx(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>Jx(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>Zx(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>Zx(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>Hx(zx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Gx(zx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>qx(zx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Dx(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function kx(){return{and:Tx({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Dx(t))return t;return t}}),or:Tx({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Dx(t))return t;return t}})}}function Ax(e,t){return{...Ox(e,t),...kx()}}function jx(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Cx(e,t)}function Mx(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function Nx(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Px(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Fx(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${Lx(t)}`);return e[t]}throw Error(`index: cannot index ${Lx(e)}`)}function Fx(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${Rx(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Ix(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=Fx(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function Lx(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Rx(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function zx(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=Bx(a,t),r=o}return n}function Bx(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Vx={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function Hx(e){return e.replace(/[\0"'&<>]/g,e=>Vx[e]??e)}const Ux={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Wx=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Gx(e){let t=``;for(let n of e){let e=Ux[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Wx.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Kx=new TextEncoder;function qx(e){let t=``,n=Kx.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function Jx(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=Yx(l??``,u,d,n,r),o=c+1}return i}function Yx(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?Xx(t,n):Xx(t,Bx(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Rx(n)}=${Bx(n,r)})`:Xx(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return Xx(t,Zx(n,r,i));case`q`:return Xx(t,JSON.stringify(Bx(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Rx(n)}=${Bx(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return Xx(t,Number(n).toFixed(i))}case`t`:return Xx(t,Dx(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return Xx(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Rx(n)}=${Bx(n,r)})`:typeof n==`bigint`?Xx(t,n.toString(16)):Xx(t,Math.trunc(n).toString(16));default:return`%!${e}(${Rx(n)}=${Bx(n,r)})`}}function Xx(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function Zx(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>Zx(e,t,n)).join(` `)}]`:e instanceof Map?Qx([...e.entries()],t,n):$x(e)?Qx(Object.entries(e),t,n):String(e)}function Qx(e,t,n){let r=e=>Zx(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function $x(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function eS(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function tS(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function nS(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function rS(e,t,n){e.vars.set(t,n)}const iS=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],aS=new Set([`default`,`zero`,`error`]);function oS(e){if(e===void 0)return`default`;if(aS.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${sS(e)}`)}function sS(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function cS(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${sS(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${sS(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${sS(e.right)}`);return{left:e.left,right:e.right}}}function lS(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function uS(e){let t=new Set(iS);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${iS.join(`, `)}`)}),lS(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const dS=Object.freeze({kind:`break`}),fS=Object.freeze({kind:`continue`}),pS={kind:`none`};let mS;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{mS=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function hS(e){let t=new Set,n=e=>{vx(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const gS={kind:`dynamic`};function _S(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=RS(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:gS}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return gS;let t=e.cmds[0];if(t===void 0)return gS;let n=t.args[0];return n===void 0||n.type!==`Identifier`?gS:{kind:`call`,name:n.ident,args:t.args.slice(1).map(_S)}}default:return gS}}function vS(e){let t=[],n=e=>{vx(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(_S);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var yS=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??DS,this.isT=e.isT??bS,this.missingKey=oS(e.missingKey),this.delims=cS(e.delims),this.funcs=uS({...Ax(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=ix(e,this.delims,t);return mS(n.source,e=>this.evalParsed(n,e),n.defines,hS(n),vS(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=eS(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw dS;case`Continue`:throw fS;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new jb(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Vb(e)}}evalIf(e,t,n){Dx(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(Dx(r)){let i=tS(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=FS(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=tS(t,o);if(i.length===1)rS(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;rS(a,e,r),rS(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===fS)continue;throw e}}}catch(e){if(e===dS)return;throw e}}evalTemplateInvoke(e,t,n){let r=nx(n.defines,e.name);if(!r)throw new jb(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=tS(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=tS(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=nx(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new jb(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,pS);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)rS(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new jb(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new jb(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new Mb(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Ex(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){SS(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof Pb?new Pb(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Lb?new Lb(t.message,r,{source:i.source}):t instanceof kb?t:new jb(`error calling ${e}: ${NS(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return RS(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new Mb(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new jb(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Sx(e,t);if(i!==bx)return i;if(this.missingKey===`error`)throw new Ib(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=nS(t,i);if(!a.found)throw new jb(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(Zx(e,this.toString,this.isT)))}};const bS=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function xS(e){return new yS(e)}function SS(e,t,n,r,i,a=DS,o=ES,s=bS){let{argTypes:c,arity:l}=t,u=CS(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new Nb(e,u,n.length,r,{source:i});let d=wS(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!TS(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new Fb(e,t+1,l,r,{source:i}):new Pb(e,t+1,MS(c),PS(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!kS(n[f],l))throw new Pb(e,t+1,`${MS(`ordered`)} of the same kind as ${PS(n[f])}`,PS(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!AS(n[p],l))throw new Pb(e,t+1,`${MS(`comparable`)} of the same kind as ${PS(n[p])}`,PS(l),r,{source:i})}}}function CS(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function wS(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function TS(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return $x(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||$x(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||$x(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||$x(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return OS(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function ES(e){return e}function DS(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new Pb(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,PS(e),{line:0,column:0,offset:0})}function OS(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function kS(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function AS(e,t){let n=jS(e),r=jS(t);return n===`nil`||r===`nil`?!0:n===r}function jS(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function MS(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function NS(e){return e instanceof Error?e.message:String(e)}function PS(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function FS(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?IS([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?IS(Object.entries(e)):[]}function IS(e){return[...e].sort((e,t)=>LS(e[0],t[0]))}function LS(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function RS(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function zS(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function BS(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function VS(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function HS(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=VS(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function US(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=VS(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function WS(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function GS(e){return JSON.stringify(e)??`null`}function KS(){return{atoi:{fn:e=>zS(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>HS(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>US(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>BS(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>WS(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>GS(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const qS={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function JS(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*qS[a],n=n.slice(e[0].length)}return t?-r:r}function YS(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<qS.us?`${Math.floor(n)}ns`:n<qS.ms?XS(n,qS.us,3,`µs`):n<qS.s?XS(n,qS.ms,6,`ms`):ZS(n),t?`-${r}`:r}function XS(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function ZS(e){let t=Math.floor(e/qS.h);e-=t*qS.h;let n=Math.floor(e/qS.m);e-=n*qS.m;let r=Math.floor(e/qS.s),i=e-r*qS.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function QS(e){return e*qS.s}function $S(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function eC(e,t){let n=t().getTime()-$S(e).getTime();return YS(Math.round(n/1e3)*1e9)}const tC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],nC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],rC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],iC=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function aC(e){return e<10?`0${e}`:String(e)}function oC(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function sC(e){return e<10?` ${e}`:String(e)}function cC(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${aC(Math.floor(n/60))}${aC(n%60)}`}function lC(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${aC(Math.floor(n/60))}:${aC(n%60)}`}function uC(e){return`${e>=0?`+`:`-`}${aC(Math.floor(Math.abs(e)/60))}`}function dC(e){return e===0?`Z`:cC(e)}function fC(e){return e===0?`Z`:lC(e)}function pC(e){return e===0?`Z`:uC(e)}function mC(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const hC=[[`.000000000`,e=>`.${mC(e.ms,9,!1)}`],[`.999999999`,e=>{let t=mC(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${mC(e.ms,6,!1)}`],[`.999999`,e=>{let t=mC(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${oC(e.ms)}`],[`.999`,e=>{let t=oC(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>tC[e.month-1]??`January`],[`Monday`,e=>rC[e.weekday]??`Monday`],[`Z07:00`,e=>fC(e.offsetMinutes)],[`-07:00`,e=>lC(e.offsetMinutes)],[`Z0700`,e=>dC(e.offsetMinutes)],[`-0700`,e=>cC(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>nC[e.month-1]??`Jan`],[`Mon`,e=>iC[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>uC(e.offsetMinutes)],[`Z07`,e=>pC(e.offsetMinutes)],[`15`,e=>aC(e.hour)],[`01`,e=>aC(e.month)],[`02`,e=>aC(e.day)],[`_2`,e=>sC(e.day)],[`03`,e=>aC(e.hour12)],[`04`,e=>aC(e.minute)],[`05`,e=>aC(e.second)],[`06`,e=>aC(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function gC(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of hC)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const _C={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function vC(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const yC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function bC(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=vC(new Intl.DateTimeFormat(`en-US`,{..._C,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=vC(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=xC(vC(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=yC.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function xC(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function SC(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function CC(e,t){return gC(e,bC($S(t),SC()))}function wC(e,t,n){return gC(e,bC($S(t),n))}function TC(e,t){let n=$S(t),r=JS(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function EC(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:YS(QS(t))}return typeof e==`bigint`?YS(QS(Number(e))):typeof e==`number`?YS(QS(e)):`0s`}const DC=36e11*24*365,OC=36e11*24*30,kC=36e11*24,AC=36e11,jC=6e10,MC=1e9;function NC(e){let t=JS(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>DC?`${Math.floor(n/DC)}y`:n>OC?`${Math.floor(n/OC)}mo`:n>kC?`${Math.floor(n/kC)}d`:n>AC?`${Math.floor(n/AC)}h`:n>jC?`${Math.floor(n/jC)}m`:n>MC?`${Math.floor(n/MC)}s`:`0s`}function PC(e){let t=bC($S(e),SC());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function FC(e,t){let n=bC($S(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function IC(e){return e()}const LC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],RC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function zC(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function BC(e,t,n){return[e.slice(t,t+n),t+n]}function VC(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function HC(e,t){for(let[n,r]of LC.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function UC(e,t){for(let[n,r]of RC.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function WC(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function GC(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function KC(e,t){if(e[t]===` `){let[n,r]=VC(e,t+1,1,1);return[n,r]}return VC(e,t,1,2)}function qC(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=VC(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=VC(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=VC(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function JC(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=VC(e,t+1,2,2);return[n*r*60,i]}return qC(e,t,n)}function YC(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function XC(e,t,n){let[r,i]=BC(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function ZC(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=HC(t,n);return i.month=e,[r,i]}case`Monday`:return[WC(t,n),i];case`Jan`:{let[e,r]=UC(t,n);return i.month=e,[r,i]}case`Mon`:return[GC(t,n),i];case`2006`:{let[e,r]=VC(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=VC(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=VC(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=VC(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=KC(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=VC(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=VC(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=VC(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=VC(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=VC(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=VC(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=VC(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=VC(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=VC(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[YC(t,n),i];case`-0700`:{let[e,r]=qC(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=qC(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=VC(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=JC(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=JC(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=JC(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=XC(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=XC(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=XC(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const QC=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function $C(e,t){let n=0,r=0,i=zC();for(;n<e.length;){let a=!1;for(let o of QC)if(e.startsWith(o,n)){let[e,s]=ZC(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function ew(e,t){return $C(e,t)}function tw(e){return String(Math.floor($S(e).getTime()/1e3))}function nw(e=()=>new Date){return{now:{fn:()=>IC(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>CC(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>wC(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>TC(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>PC(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>FC(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>EC(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>NC(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>ew(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>eC(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>tw(e),argTypes:[`value`],arity:{kind:`exact`}}}}function rw(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function iw(...e){for(let t of e)if(!rw(t))return t}function aw(e,t){return rw(t)?e:t}function ow(e){return JSON.parse(e)}function sw(e,t,n){return Dx(n)?e:t}function cw(e){return JSON.stringify(e)??`null`}function lw(e){return JSON.stringify(e,null,2)??`null`}function uw(){return{default:{fn:(e,t)=>aw(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>rw(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>iw(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>sw(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>ow(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>cw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>lw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function dw(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function fw(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return dw(...t)}function pw(e,t){return e[t]}function mw(e,t){return t in e}function hw(e){return Object.keys(e)}function gw(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function _w(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function vw(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function yw(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function bw(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function xw(e,t,n){return e[t]=n,e}function Sw(e,t){return delete e[t],e}function Cw(e){return Object.values(e)}function ww(){return{dict:{fn:(...e)=>dw(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>pw(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>xw(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>Sw(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>hw(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>Cw(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>bw(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>yw(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>vw(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>mw(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>gw(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>_w(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function Tw(e){throw new Lb(e)}function Ew(){return{fail:{fn:e=>Tw(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function Dw(...e){for(let t of e)if(rw(t))return!1;return!0}function Ow(...e){for(let t of e)if(!rw(t))return!0;return!1}function kw(e,t){return[...e,t]}function Aw(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function jw(e){return e.filter(e=>!rw(e))}function Mw(...e){let t=[];for(let n of e)t.push(...n);return t}const Nw={line:0,column:0,offset:0};function Pw(e,t,n,r){return new Pb(e,t,n,r,Nw)}function Fw(...e){if(e.length<3)throw Pw(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!Lw(t))throw Pw(`dig`,e.length-1,`dict`,Rw(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Pw(`dig`,e,`string`,Rw(r[e]));return Iw(t,n,r,e.length)}function Iw(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!Lw(a))throw Pw(`dig`,r-1,`dict at intermediate key`,Rw(a));return Iw(a,t,n.slice(1),r)}function Lw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Rw(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function zw(e){return e[0]}function Bw(e,t){return t.some(t=>Cx(t,e))}function Vw(e){return e.slice(0,-1)}function Hw(e){return e[e.length-1]}function Uw(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Ww(...e){return e}function Gw(e,t){return[t,...e]}function Kw(e){return e.slice(1)}function qw(e){return[...e].reverse()}function Jw(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Yw(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Xw(e){let t=[];for(let n of e)t.some(e=>Cx(e,n))||t.push(n);return t}function Zw(e,...t){return e.filter(e=>!t.some(t=>Cx(t,e)))}function Qw(){return{list:{fn:(...e)=>Ww(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>zw(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>Hw(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>Kw(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>Vw(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>Uw(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>qw(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>Xw(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>Zw(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>Bw(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>jw(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>Jw(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>Mw(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Aw(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>Gw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>kw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>Yw(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>kw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>Ww(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>Fw(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>Dw(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>Ow(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function $w(...e){return e.reduce((e,t)=>e+t,0)}function eT(e){return e+1}function tT(e){return e+1}function nT(...e){return e.reduce((e,t)=>e+t,0)}function rT(e){return Math.ceil(e)}function iT(e,t){return Math.trunc(e/t)}function aT(e,...t){return t.reduce((e,t)=>e/t,e)}function oT(e){return Math.floor(e)}function sT(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function cT(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function lT(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function uT(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function dT(e,t){return e%t}function fT(...e){return e.reduce((e,t)=>e*t,1)}function pT(...e){return e.reduce((e,t)=>e*t,1)}function mT(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function hT(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function gT(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),hT(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return hT(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:hT(n,i+t,r).join(` `)}default:return``}}function _T(e,t){return e-t}function vT(e,...t){return t.reduce((e,t)=>e-t,e)}function yT(e){return hT(0,e,e<0?-1:1)}function bT(){return{add:{fn:(...e)=>$w(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>_T(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>fT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>iT(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>dT(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>lT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>sT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>oT(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>rT(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>mT(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>nT(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>vT(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>pT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>aT(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>eT(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>tT(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>cT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>uT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>sT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>gT(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>yT(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>hT(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function xT(e){return Array.from(e)}function ST(e,t){return e===``?xT(t):t.split(e)}function CT(e,t){let n=xT(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function wT(e,t,n){let r=xT(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const Y={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},TT=/^[-_\s]$/,ET=/^\p{P}$/u,DT=/^\p{L}$/u,OT=/^\p{Lu}$/u,kT=/^\p{N}$/u;function AT(e){return e!==void 0&&TT.test(e)}function jT(e){return e!==void 0&&DT.test(e)}function MT(e){return e!==void 0&&OT.test(e)}function NT(e){return e!==void 0&&kT.test(e)}function PT(e){return e!==void 0&&ET.test(e)}function FT(e,t){if(t>=e.length)return{word:{wt:Y.Invalid,text:``},next:t};let n=e[t],r=t+1;if(AT(n)){for(;r<e.length&&AT(e[r]);)r++;return{word:{wt:Y.Connector,text:e.slice(t,r).join(``)},next:r}}if(PT(n)){for(;r<e.length&&PT(e[r]);)r++;return{word:{wt:Y.Punct,text:e.slice(t,r).join(``)},next:r}}if(MT(n)){if(r>=e.length)return{word:{wt:Y.UpperCase,text:n},next:r};if(MT(e[r])){let n=r;for(;n<e.length&&MT(e[n]);)n++;return n<e.length&&jT(e[n])?{word:{wt:Y.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(jT(e[r])){let n=r+1;for(;n<e.length&&jT(e[n])&&!MT(e[n]);)n++;return{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:Y.UpperCase,text:n},next:r}}if(jT(n)){for(;r<e.length&&jT(e[r])&&!MT(e[r]);)r++;return{word:{wt:Y.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(NT(n)){for(;r<e.length&&NT(e[r]);)r++;return{word:{wt:Y.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!AT(e[r])&&!jT(e[r])&&!NT(e[r])&&!PT(e[r]);)r++;return{word:{wt:Y.Other,text:e.slice(t,r).join(``)},next:r}}function IT(e,t,n){if(t.wt!==Y.UpperCase&&t.wt!==Y.Connector){e.push(t.text);return}for(let r of t.text)AT(r)?e.push(n):MT(r)?e.push(r.toLowerCase()):e.push(r)}function LT(e,t){if(e.length===0)return``;let n=xT(e),r=[],{word:i,next:a}=FT(n,0);for(;a<n.length;){i.wt!==Y.Connector&&IT(r,i,t);let e=i,o=i;if({word:i,next:a}=FT(n,a),e.wt===Y.Number){for(;i.wt===Y.Alphabet||i.wt===Y.Number;)IT(r,i,t),{word:i,next:a}=FT(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Punct&&i.wt!==Y.Connector&&r.push(t);continue}if(e.wt===Y.Connector){IT(r,o,t);continue}if(e.wt===Y.Punct)continue;if(i.wt!==Y.Number){i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=FT(n,a),i.wt!==Y.Alphabet){IT(r,s,t),i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}for(r.push(t),IT(r,s,t);i.wt===Y.Alphabet||i.wt===Y.Number;)IT(r,i,t),{word:i,next:a}=FT(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t)}return IT(r,i,t),r.join(``).toLowerCase()}function RT(e){if(e.length===0)return``;let t=xT(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!AT(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,AT(i)&&AT(e)){n.push(e);continue}AT(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function zT(e){return RT(e)}function BT(...e){return e.join(` `)}function VT(e,t){return t.includes(e)}function HT(e,t){return t.startsWith(e)}function UT(e,t){return t.endsWith(e)}function WT(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
66
|
+
`?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function Zb(e){return e===` `||e===` `||e===`\r`||e===`
|
|
67
|
+
`}function Qb(e){return e===`+`||e===`-`}function $b(e){return e>=`0`&&e<=`9`}function ex(e){return $b(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function tx(e){return e>=`0`&&e<=`7`}function nx(e){return e===`0`||e===`1`}function rx(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function ix(e){return rx(e)||e===`_`}function ax(e){return ix(e)||$b(e)}let ox,sx;function cx(e,t){return sx(e,t)}var lx=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{ox=(t,n)=>new e(t,n),sx=(e,t)=>e.#e.get(t)??(e.#t&&sx(e.#t,t))}has(e){return sx(this,e)!==void 0}};function ux(e,t,n=lx.EMPTY){return new dx(e,t,n).parseTemplate()}var dx=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new Xb(e,t):new Xb(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:mx(n)});return n}errAt(e,t,n={}){return new Ib(t,e.pos,{...n,source:this.source})}parseTemplate(){let e=this.parseList();if(this.peek().type!==`EOF`){let e=this.peek(),t=this.peek(1);if(e.type===`LeftDelim`&&(t.type===`Else`||t.type===`End`)){let n=t.type===`Else`?`else`:`end`;throw this.errAt(e,`unexpected \`{{${n}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``,{found:`{{${n}}}`})}throw this.errAt(e,`unexpected ${mx(e)}`,{found:mx(e)})}return{root:e,defines:ox(this.defines,this.inherit),ownDefines:this.defines,source:this.source}}parseList(){let e=this.peek().pos,t=[];for(;;){let n=this.peek();if(n.type===`EOF`)break;if(n.type===`Text`){this.next(),t.push({type:`Text`,pos:n.pos,text:n.value});continue}if(n.type===`Comment`){this.next();let e=px(n);t.push({type:`Comment`,pos:n.pos,text:n.value,trim:e});continue}if(n.type===`LeftDelim`){let n=this.peek(1).type;if(n===`Else`||n===`End`)return fx(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${mx(n)} at top level`,{found:mx(n)})}return fx(e,t)}parseAction(){let e=this.expect(`LeftDelim`,"`{{`"),t=e.trimLeft===!0,n=this.peek();switch(n.type){case`If`:return this.next(),this.parseBranch(`If`,e.pos,t);case`Range`:return this.next(),this.parseBranch(`Range`,e.pos,t);case`With`:return this.next(),this.parseBranch(`With`,e.pos,t);case`Break`:return this.next(),this.parseBreakOrContinue(`Break`,e.pos,t);case`Continue`:return this.next(),this.parseBreakOrContinue(`Continue`,e.pos,t);case`Template`:return this.next(),this.parseTemplateInvocation(e.pos,t);case`Block`:return this.next(),this.parseBlock(e.pos,t);case`Define`:return this.next(),this.parseDefine(e.pos,t),null;case`RightDelim`:throw this.errAt(n,`empty action`,{expected:`pipeline`});default:{let n=this.parsePipeline(),r=this.expect(`RightDelim`,"`}}`");return{type:`Action`,pos:e.pos,pipe:n,trim:{trimLeft:t,trimRight:r.trimRight===!0}}}}}parseBranch(e,t,n){let r=this.parsePipeline();this.expect(`RightDelim`,"`}}`"),e===`Range`&&(this.rangeDepth+=1);let i=this.parseList();e===`Range`&&--this.rangeDepth;let a=this.parseElsePart(),o={trimLeft:n,trimRight:a.endConsumed?a.endRight:this.consumeEnd()},s=a.list?{pipe:r,list:i,elseList:a.list,trim:o}:{pipe:r,list:i,trim:o};switch(e){case`If`:return{type:`If`,pos:t,...s};case`Range`:return{type:`Range`,pos:t,...s};case`With`:return{type:`With`,pos:t,...s}}}parseBreakOrContinue(e,t,n){if(this.rangeDepth===0)throw new Ib(`{{${e===`Break`?`break`:`continue`}}} outside of {{range}}`,t,{source:this.source});let r={trimLeft:n,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return e===`Break`?{type:`Break`,pos:t,trim:r}:{type:`Continue`,pos:t,trim:r}}parseElsePart(){if(this.peek().type!==`LeftDelim`||this.peek(1).type!==`Else`)return{list:void 0,endRight:!1,endConsumed:!1};let e=this.next();if(this.next(),this.peek().type===`If`){this.next();let t=this.parseBranch(`If`,e.pos,e.trimLeft===!0);return{list:{type:`List`,pos:e.pos,nodes:[t]},endRight:t.trim.trimRight,endConsumed:!0}}return this.expect(`RightDelim`,"`}}`"),{list:this.parseList(),endRight:!1,endConsumed:!1}}consumeEnd(){return this.expect(`LeftDelim`,"`{{end}}`"),this.expect(`End`,"`end`"),this.expect(`RightDelim`,"`}}`").trimRight===!0}parseTemplateInvocation(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline(),i={trimLeft:t,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return r?{type:`Template`,pos:e,name:n,pipe:r,trim:i}:{type:`Template`,pos:e,name:n,trim:i}}parseBlock(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline();this.expect(`RightDelim`,"`}}`");let i=this.rangeDepth;this.rangeDepth=0;let a=this.parseList();this.rangeDepth=i;let o={trimLeft:t,trimRight:this.consumeEnd()};return!this.defines.has(n)&&!this.inherit.has(n)&&this.defines.set(n,{list:a,source:this.source}),r?{type:`Block`,pos:e,name:n,pipe:r,list:a,trim:o}:{type:`Block`,pos:e,name:n,list:a,trim:o}}parseDefine(e,t){let n=this.parseQuotedName();this.expect(`RightDelim`,"`}}`");let r=this.rangeDepth;this.rangeDepth=0;let i=this.parseList();if(this.rangeDepth=r,this.consumeEnd(),this.defines.has(n)||this.inherit.has(n))throw new Ib(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,{list:i,source:this.source})}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:mx(e)});return Sx(e.value,e.pos,this.source)}parsePipeline(){let e=this.peek().pos,t=this.tryParseDecls(),n=[this.parseCommand()];for(;this.peek().type===`Pipe`;){this.next();let e=this.peek();if(!hx(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:mx(e)});n.push(this.parseCommand())}return{type:`Pipe`,pos:e,decls:t?.vars??[],isAssign:t?.isAssign??!1,cmds:n}}tryParseDecls(){if(this.peek().type!==`Variable`)return;let e=1;for(;this.peek(e).type===`Comma`;){if(this.peek(e+1).type!==`Variable`)return;e+=2}let t=this.peek(e).type;if(t!==`Declare`&&t!==`Assign`)return;let n=[gx(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(gx(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;hx(this.peek().type);)t.push(this.parsePrimary());return{type:`Command`,pos:e,args:t}}parsePrimary(){let e=this.next();switch(e.type){case`Dot`:return{type:`Dot`,pos:e.pos};case`Field`:return{type:`Field`,pos:e.pos,idents:e.value.slice(1).split(`.`)};case`Variable`:return gx(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Sx(e.value,e.pos,this.source)};case`Number`:return vx(e);case`Char`:return yx(e,this.source);case`Bool`:return{type:`Bool`,pos:e.pos,value:e.value===`true`};case`Nil`:return{type:`Nil`,pos:e.pos};case`LeftParen`:return this.parseChainOrPipe(e.pos);default:throw this.errAt(e,`expected command argument, found ${mx(e)}`,{expected:`command argument`,found:mx(e)})}}parseChainOrPipe(e){let t=this.parsePipeline(),n=this.expect(`RightParen`,"`)`"),r=[],i=n.pos.offset+1,a=this.peek();return a.type===`Field`&&a.pos.offset===i&&(this.next(),r.push(...a.value.slice(1).split(`.`))),r.length===0?t:{type:`Chain`,pos:e,node:t,fields:r}}};function fx(e,t){return{type:`List`,pos:e,nodes:t}}function px(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function mx(e){return e.type===`EOF`?`end of input`:e.value||e.type}function hx(e){switch(e){case`Dot`:case`Field`:case`Variable`:case`Identifier`:case`String`:case`Number`:case`Char`:case`Bool`:case`Nil`:case`LeftParen`:return!0;default:return!1}}function gx(e){return{type:`Variable`,pos:e.pos,idents:_x(e.value)}}function _x(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function vx(e){let t=e.value,n=t.replace(/_/g,``),r=n.toLowerCase().endsWith(`i`),i=r?n.slice(0,-1):n,a=!r&&(i.includes(`.`)||!i.startsWith(`0x`)&&!i.startsWith(`0X`)&&/[eE]/.test(i)||(i.startsWith(`0x`)||i.startsWith(`0X`))&&/[pP]/.test(i)),o=!r&&!a,s={type:`Number`,pos:e.pos,text:t,isInt:o,isUint:!1,isFloat:a,isComplex:r};if(o){let e=bx(i);return{...s,intValue:e}}if(a){let e=xx(i);return{...s,floatValue:e}}let c=xx(i);return{...s,complexValue:[0,c]}}function yx(e,t){let n=Cx(e.value,e.pos,t);return{type:`Number`,pos:e.pos,text:e.value,isInt:!0,isUint:!1,isFloat:!1,isComplex:!1,intValue:BigInt(n)}}function bx(e){let t=1n,n=e;return n.startsWith(`+`)?n=n.slice(1):n.startsWith(`-`)&&(t=-1n,n=n.slice(1)),t*BigInt(n)}function xx(e){return Number(e)}function Sx(e,t,n){if(e.startsWith("`"))return e.slice(1,-1);let r=``;for(let i=1;i<e.length-1;i++){let a=e[i];if(a!==`\\`){r+=a;continue}let o=e[++i];switch(o){case`n`:r+=`
|
|
68
|
+
`;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new Ib(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Cx(e,t,n){let r=Sx(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Ib(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function wx(e,t){if(t(e)!==!1)for(let n of Tx(e))wx(n,t)}function Tx(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return qb(e)}}const Ex=Symbol(`go-template-js.MISSING`);function Dx(e,t){if(e==null)return Ex;if(e instanceof Map)return e.has(t)?e.get(t):Ex;if(Array.isArray(e))return Ex;if(typeof e==`object`){let n=e;return t in n?n[t]:Ex}return Ex}function Ox(e,t){let n=e;for(let e of t){if(n===Ex)return Ex;n=Dx(n,e)}return n}function kx(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>kx(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!kx(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>kx(e[n],t[n])):!1}return!1}const Ax=new WeakSet;function jx(e){return Ax.add(e),e}function Mx(e){return Ax.has(e)}function Nx(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function Px(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Lx(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Lx(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Rx(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Rx(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Rx(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Rx(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>zx(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Bx(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Hx(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Gx(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Gx(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>eS(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>rS(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>rS(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>Jx(Gx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Zx(Gx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>$x(Gx(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Nx(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Fx(){return{and:jx({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Nx(t))return t;return t}}),or:jx({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Nx(t))return t;return t}})}}function Ix(e,t){return{...Px(e,t),...Fx()}}function Lx(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):kx(e,t)}function Rx(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function zx(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Bx(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Vx(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${Ux(t)}`);return e[t]}throw Error(`index: cannot index ${Ux(e)}`)}function Vx(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${Wx(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Hx(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=Vx(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function Ux(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Wx(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function Gx(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=Kx(a,t),r=o}return n}function Kx(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const qx={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function Jx(e){return e.replace(/[\0"'&<>]/g,e=>qx[e]??e)}const Yx={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Xx=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Zx(e){let t=``;for(let n of e){let e=Yx[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Xx.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Qx=new TextEncoder;function $x(e){let t=``,n=Qx.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function eS(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=tS(l??``,u,d,n,r),o=c+1}return i}function tS(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?nS(t,n):nS(t,Kx(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Wx(n)}=${Kx(n,r)})`:nS(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return nS(t,rS(n,r,i));case`q`:return nS(t,JSON.stringify(Kx(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Wx(n)}=${Kx(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return nS(t,Number(n).toFixed(i))}case`t`:return nS(t,Nx(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return nS(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Wx(n)}=${Kx(n,r)})`:typeof n==`bigint`?nS(t,n.toString(16)):nS(t,Math.trunc(n).toString(16));default:return`%!${e}(${Wx(n)}=${Kx(n,r)})`}}function nS(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function rS(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>rS(e,t,n)).join(` `)}]`:e instanceof Map?iS([...e.entries()],t,n):aS(e)?iS(Object.entries(e),t,n):String(e)}function iS(e,t,n){let r=e=>rS(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function aS(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function oS(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function sS(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function cS(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function lS(e,t,n){e.vars.set(t,n)}const uS=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],dS=new Set([`default`,`zero`,`error`]);function fS(e){if(e===void 0)return`default`;if(dS.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${pS(e)}`)}function pS(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function mS(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${pS(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${pS(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${pS(e.right)}`);return{left:e.left,right:e.right}}}function hS(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function gS(e){let t=new Set(uS);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${uS.join(`, `)}`)}),hS(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const _S=Object.freeze({kind:`break`}),vS=Object.freeze({kind:`continue`}),yS={kind:`none`};let bS;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{bS=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function xS(e){let t=new Set,n=e=>{wx(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const SS={kind:`dynamic`};function CS(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=WS(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:SS}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return SS;let t=e.cmds[0];if(t===void 0)return SS;let n=t.args[0];return n===void 0||n.type!==`Identifier`?SS:{kind:`call`,name:n.ident,args:t.args.slice(1).map(CS)}}default:return SS}}function wS(e){let t=[],n=e=>{wx(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(CS);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var TS=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??NS,this.isT=e.isT??ES,this.missingKey=fS(e.missingKey),this.delims=mS(e.delims),this.funcs=gS({...Ix(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=ux(e,this.delims,t);return bS(n.source,e=>this.evalParsed(n,e),n.defines,xS(n),wS(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=oS(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw _S;case`Continue`:throw vS;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new Lb(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:qb(e)}}evalIf(e,t,n){Nx(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(Nx(r)){let i=sS(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=VS(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=sS(t,o);if(i.length===1)lS(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;lS(a,e,r),lS(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===vS)continue;throw e}}}catch(e){if(e===_S)return;throw e}}evalTemplateInvoke(e,t,n){let r=cx(n.defines,e.name);if(!r)throw new Lb(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=sS(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=sS(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=cx(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Lb(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,yS);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)lS(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new Lb(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Lb(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new Rb(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Mx(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){OS(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof Bb?new Bb(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Ub?new Ub(t.message,r,{source:i.source}):t instanceof Fb?t:new Lb(`error calling ${e}: ${zS(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return WS(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new Rb(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new Lb(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Ox(e,t);if(i!==Ex)return i;if(this.missingKey===`error`)throw new Hb(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=cS(t,i);if(!a.found)throw new Lb(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(rS(e,this.toString,this.isT)))}};const ES=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function DS(e){return new TS(e)}function OS(e,t,n,r,i,a=NS,o=MS,s=ES){let{argTypes:c,arity:l}=t,u=kS(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new zb(e,u,n.length,r,{source:i});let d=AS(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!jS(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new Vb(e,t+1,l,r,{source:i}):new Bb(e,t+1,RS(c),BS(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!FS(n[f],l))throw new Bb(e,t+1,`${RS(`ordered`)} of the same kind as ${BS(n[f])}`,BS(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!IS(n[p],l))throw new Bb(e,t+1,`${RS(`comparable`)} of the same kind as ${BS(n[p])}`,BS(l),r,{source:i})}}}function kS(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function AS(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function jS(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return aS(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||aS(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||aS(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||aS(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return PS(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function MS(e){return e}function NS(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new Bb(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,BS(e),{line:0,column:0,offset:0})}function PS(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function FS(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function IS(e,t){let n=LS(e),r=LS(t);return n===`nil`||r===`nil`?!0:n===r}function LS(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function RS(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function zS(e){return e instanceof Error?e.message:String(e)}function BS(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function VS(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?HS([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?HS(Object.entries(e)):[]}function HS(e){return[...e].sort((e,t)=>US(e[0],t[0]))}function US(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function WS(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function GS(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function KS(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function qS(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function JS(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=qS(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function YS(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=qS(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function XS(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function ZS(e){return JSON.stringify(e)??`null`}function QS(){return{atoi:{fn:e=>GS(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>JS(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>YS(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>KS(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>XS(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>ZS(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const $S={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function eC(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*$S[a],n=n.slice(e[0].length)}return t?-r:r}function tC(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<$S.us?`${Math.floor(n)}ns`:n<$S.ms?nC(n,$S.us,3,`µs`):n<$S.s?nC(n,$S.ms,6,`ms`):rC(n),t?`-${r}`:r}function nC(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function rC(e){let t=Math.floor(e/$S.h);e-=t*$S.h;let n=Math.floor(e/$S.m);e-=n*$S.m;let r=Math.floor(e/$S.s),i=e-r*$S.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function iC(e){return e*$S.s}function aC(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function oC(e,t){let n=t().getTime()-aC(e).getTime();return tC(Math.round(n/1e3)*1e9)}const sC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],cC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],lC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],uC=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function dC(e){return e<10?`0${e}`:String(e)}function fC(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function pC(e){return e<10?` ${e}`:String(e)}function mC(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${dC(Math.floor(n/60))}${dC(n%60)}`}function hC(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${dC(Math.floor(n/60))}:${dC(n%60)}`}function gC(e){return`${e>=0?`+`:`-`}${dC(Math.floor(Math.abs(e)/60))}`}function _C(e){return e===0?`Z`:mC(e)}function vC(e){return e===0?`Z`:hC(e)}function yC(e){return e===0?`Z`:gC(e)}function bC(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const xC=[[`.000000000`,e=>`.${bC(e.ms,9,!1)}`],[`.999999999`,e=>{let t=bC(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${bC(e.ms,6,!1)}`],[`.999999`,e=>{let t=bC(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${fC(e.ms)}`],[`.999`,e=>{let t=fC(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>sC[e.month-1]??`January`],[`Monday`,e=>lC[e.weekday]??`Monday`],[`Z07:00`,e=>vC(e.offsetMinutes)],[`-07:00`,e=>hC(e.offsetMinutes)],[`Z0700`,e=>_C(e.offsetMinutes)],[`-0700`,e=>mC(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>cC[e.month-1]??`Jan`],[`Mon`,e=>uC[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>gC(e.offsetMinutes)],[`Z07`,e=>yC(e.offsetMinutes)],[`15`,e=>dC(e.hour)],[`01`,e=>dC(e.month)],[`02`,e=>dC(e.day)],[`_2`,e=>pC(e.day)],[`03`,e=>dC(e.hour12)],[`04`,e=>dC(e.minute)],[`05`,e=>dC(e.second)],[`06`,e=>dC(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function SC(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of xC)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const CC={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function wC(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const TC=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function EC(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=wC(new Intl.DateTimeFormat(`en-US`,{...CC,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=wC(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=DC(wC(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=TC.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function DC(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function OC(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function kC(e,t){return SC(e,EC(aC(t),OC()))}function AC(e,t,n){return SC(e,EC(aC(t),n))}function jC(e,t){let n=aC(t),r=eC(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function MC(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:tC(iC(t))}return typeof e==`bigint`?tC(iC(Number(e))):typeof e==`number`?tC(iC(e)):`0s`}const NC=36e11*24*365,PC=36e11*24*30,FC=36e11*24,IC=36e11,LC=6e10,RC=1e9;function zC(e){let t=eC(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>NC?`${Math.floor(n/NC)}y`:n>PC?`${Math.floor(n/PC)}mo`:n>FC?`${Math.floor(n/FC)}d`:n>IC?`${Math.floor(n/IC)}h`:n>LC?`${Math.floor(n/LC)}m`:n>RC?`${Math.floor(n/RC)}s`:`0s`}function BC(e){let t=EC(aC(e),OC());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function VC(e,t){let n=EC(aC(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function HC(e){return e()}const UC=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],WC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function GC(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function KC(e,t,n){return[e.slice(t,t+n),t+n]}function qC(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function JC(e,t){for(let[n,r]of UC.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function YC(e,t){for(let[n,r]of WC.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function XC(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function ZC(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function QC(e,t){if(e[t]===` `){let[n,r]=qC(e,t+1,1,1);return[n,r]}return qC(e,t,1,2)}function $C(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=qC(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=qC(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=qC(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function ew(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=qC(e,t+1,2,2);return[n*r*60,i]}return $C(e,t,n)}function tw(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function nw(e,t,n){let[r,i]=KC(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function rw(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=JC(t,n);return i.month=e,[r,i]}case`Monday`:return[XC(t,n),i];case`Jan`:{let[e,r]=YC(t,n);return i.month=e,[r,i]}case`Mon`:return[ZC(t,n),i];case`2006`:{let[e,r]=qC(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=qC(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=qC(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=qC(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=QC(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=qC(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=qC(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=qC(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=qC(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=qC(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=qC(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=qC(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=qC(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=qC(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[tw(t,n),i];case`-0700`:{let[e,r]=$C(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=$C(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=qC(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=ew(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=ew(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=ew(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=nw(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=nw(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=nw(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const iw=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function aw(e,t){let n=0,r=0,i=GC();for(;n<e.length;){let a=!1;for(let o of iw)if(e.startsWith(o,n)){let[e,s]=rw(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function ow(e,t){return aw(e,t)}function sw(e){return String(Math.floor(aC(e).getTime()/1e3))}function cw(e=()=>new Date){return{now:{fn:()=>HC(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>kC(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>AC(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>jC(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>BC(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>VC(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>MC(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>zC(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>ow(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>oC(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>sw(e),argTypes:[`value`],arity:{kind:`exact`}}}}function lw(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function uw(...e){for(let t of e)if(!lw(t))return t}function dw(e,t){return lw(t)?e:t}function fw(e){return JSON.parse(e)}function pw(e,t,n){return Nx(n)?e:t}function mw(e){return JSON.stringify(e)??`null`}function hw(e){return JSON.stringify(e,null,2)??`null`}function gw(){return{default:{fn:(e,t)=>dw(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>lw(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>uw(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>pw(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>fw(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>mw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>hw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function _w(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function vw(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return _w(...t)}function yw(e,t){return e[t]}function bw(e,t){return t in e}function xw(e){return Object.keys(e)}function Sw(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function Cw(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function ww(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function Tw(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Ew(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function Dw(e,t,n){return e[t]=n,e}function Ow(e,t){return delete e[t],e}function kw(e){return Object.values(e)}function Aw(){return{dict:{fn:(...e)=>_w(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>yw(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>Dw(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>Ow(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>xw(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>kw(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>Ew(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>Tw(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>ww(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>bw(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>Sw(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>Cw(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function jw(e){throw new Ub(e)}function Mw(){return{fail:{fn:e=>jw(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function Nw(...e){for(let t of e)if(lw(t))return!1;return!0}function Pw(...e){for(let t of e)if(!lw(t))return!0;return!1}function Fw(e,t){return[...e,t]}function Iw(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function Lw(e){return e.filter(e=>!lw(e))}function Rw(...e){let t=[];for(let n of e)t.push(...n);return t}const zw={line:0,column:0,offset:0};function Bw(e,t,n,r){return new Bb(e,t,n,r,zw)}function Vw(...e){if(e.length<3)throw Bw(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!Uw(t))throw Bw(`dig`,e.length-1,`dict`,Ww(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Bw(`dig`,e,`string`,Ww(r[e]));return Hw(t,n,r,e.length)}function Hw(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!Uw(a))throw Bw(`dig`,r-1,`dict at intermediate key`,Ww(a));return Hw(a,t,n.slice(1),r)}function Uw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Ww(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Gw(e){return e[0]}function Kw(e,t){return t.some(t=>kx(t,e))}function qw(e){return e.slice(0,-1)}function Jw(e){return e[e.length-1]}function Yw(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Xw(...e){return e}function Zw(e,t){return[t,...e]}function Qw(e){return e.slice(1)}function $w(e){return[...e].reverse()}function eT(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function tT(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function nT(e){let t=[];for(let n of e)t.some(e=>kx(e,n))||t.push(n);return t}function rT(e,...t){return e.filter(e=>!t.some(t=>kx(t,e)))}function iT(){return{list:{fn:(...e)=>Xw(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>Gw(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>Jw(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>Qw(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>qw(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>Yw(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>$w(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>nT(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>rT(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>Kw(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>Lw(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>eT(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>Rw(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Iw(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>Zw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>Fw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>tT(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>Fw(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>Xw(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>Vw(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>Nw(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>Pw(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function aT(...e){return e.reduce((e,t)=>e+t,0)}function oT(e){return e+1}function sT(e){return e+1}function cT(...e){return e.reduce((e,t)=>e+t,0)}function lT(e){return Math.ceil(e)}function uT(e,t){return Math.trunc(e/t)}function dT(e,...t){return t.reduce((e,t)=>e/t,e)}function fT(e){return Math.floor(e)}function pT(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function mT(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function hT(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function gT(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function _T(e,t){return e%t}function vT(...e){return e.reduce((e,t)=>e*t,1)}function yT(...e){return e.reduce((e,t)=>e*t,1)}function bT(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function xT(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function ST(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),xT(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return xT(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:xT(n,i+t,r).join(` `)}default:return``}}function CT(e,t){return e-t}function wT(e,...t){return t.reduce((e,t)=>e-t,e)}function TT(e){return xT(0,e,e<0?-1:1)}function ET(){return{add:{fn:(...e)=>aT(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>CT(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>vT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>uT(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>_T(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>hT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>pT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>fT(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>lT(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>bT(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>cT(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>wT(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>yT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>dT(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>oT(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>sT(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>mT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>gT(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>pT(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>ST(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>TT(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>xT(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function DT(e){return Array.from(e)}function OT(e,t){return e===``?DT(t):t.split(e)}function kT(e,t){let n=DT(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function AT(e,t,n){let r=DT(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const Y={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},jT=/^[-_\s]$/,MT=/^\p{P}$/u,NT=/^\p{L}$/u,PT=/^\p{Lu}$/u,FT=/^\p{N}$/u;function IT(e){return e!==void 0&&jT.test(e)}function LT(e){return e!==void 0&&NT.test(e)}function RT(e){return e!==void 0&&PT.test(e)}function zT(e){return e!==void 0&&FT.test(e)}function BT(e){return e!==void 0&&MT.test(e)}function VT(e,t){if(t>=e.length)return{word:{wt:Y.Invalid,text:``},next:t};let n=e[t],r=t+1;if(IT(n)){for(;r<e.length&&IT(e[r]);)r++;return{word:{wt:Y.Connector,text:e.slice(t,r).join(``)},next:r}}if(BT(n)){for(;r<e.length&&BT(e[r]);)r++;return{word:{wt:Y.Punct,text:e.slice(t,r).join(``)},next:r}}if(RT(n)){if(r>=e.length)return{word:{wt:Y.UpperCase,text:n},next:r};if(RT(e[r])){let n=r;for(;n<e.length&&RT(e[n]);)n++;return n<e.length&<(e[n])?{word:{wt:Y.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(LT(e[r])){let n=r+1;for(;n<e.length&<(e[n])&&!RT(e[n]);)n++;return{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:Y.UpperCase,text:n},next:r}}if(LT(n)){for(;r<e.length&<(e[r])&&!RT(e[r]);)r++;return{word:{wt:Y.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(zT(n)){for(;r<e.length&&zT(e[r]);)r++;return{word:{wt:Y.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!IT(e[r])&&!LT(e[r])&&!zT(e[r])&&!BT(e[r]);)r++;return{word:{wt:Y.Other,text:e.slice(t,r).join(``)},next:r}}function HT(e,t,n){if(t.wt!==Y.UpperCase&&t.wt!==Y.Connector){e.push(t.text);return}for(let r of t.text)IT(r)?e.push(n):RT(r)?e.push(r.toLowerCase()):e.push(r)}function UT(e,t){if(e.length===0)return``;let n=DT(e),r=[],{word:i,next:a}=VT(n,0);for(;a<n.length;){i.wt!==Y.Connector&&HT(r,i,t);let e=i,o=i;if({word:i,next:a}=VT(n,a),e.wt===Y.Number){for(;i.wt===Y.Alphabet||i.wt===Y.Number;)HT(r,i,t),{word:i,next:a}=VT(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Punct&&i.wt!==Y.Connector&&r.push(t);continue}if(e.wt===Y.Connector){HT(r,o,t);continue}if(e.wt===Y.Punct)continue;if(i.wt!==Y.Number){i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=VT(n,a),i.wt!==Y.Alphabet){HT(r,s,t),i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}for(r.push(t),HT(r,s,t);i.wt===Y.Alphabet||i.wt===Y.Number;)HT(r,i,t),{word:i,next:a}=VT(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t)}return HT(r,i,t),r.join(``).toLowerCase()}function WT(e){if(e.length===0)return``;let t=DT(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!IT(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,IT(i)&&IT(e)){n.push(e);continue}IT(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function GT(e){return WT(e)}function KT(...e){return e.join(` `)}function qT(e,t){return t.includes(e)}function JT(e,t){return t.startsWith(e)}function YT(e,t){return t.endsWith(e)}function XT(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
69
69
|
`).map(e=>n+e).join(`
|
|
70
|
-
`)}function
|
|
71
|
-
`,t)}function
|
|
72
|
-
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function CE(e,t,n){return SE(e,t,n)}function wE(){return{abbrev:{fn:(e,t)=>CT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>wT(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>zT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>BT(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>VT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>HT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>UT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>WT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>GT(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>KT(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>JT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>YT(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>XT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>ZT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>QT(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>$T(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>eE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>tE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>nE(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>rE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>iE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>aE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>oE(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>cE(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>lE(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>uE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>pE(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>mE(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>hE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>gE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>_E(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>vE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>yE(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>bE(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>xE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>CE(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function TE(e,t){let n=EE(e),r=n.copy();return r.style=Su(n.style,t),r}function EE(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function DE(e){return{fn:(t=>TE(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function OE(e){return{fn:((t,n)=>TE(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function kE(e,t){return new H({[e]:t})}function AE(){let e={};for(let t of gu)e[t]=DE(kE(t,!0)),e[`not_${t}`]=DE(kE(t,!1));for(let[t,n]of Object.entries(vu))e[t]=DE(kE(n,!0));return e}const jE={fn:((e,t)=>TE(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},ME={fn:((e,t)=>TE(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function NE(){return{fg:OE(`color`),bg:OE(`bgcolor`),...AE(),link:ME,style:jE}}function PE(e,t){let n;try{n=rc(e.trim())}catch(n){throw n instanceof zs?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return FE(n,t,JSON.stringify(e))}function FE(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function IE(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function LE(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const RE=IE([`string`,`int`],((e,t)=>Bc(PE(e,`darken`),t).hex)),zE=IE([`string`,`int`],((e,t)=>Bc(PE(e,`lighten`),-t).hex)),BE={min:0,max:100,note:`0 = from, 100 = toward`},VE=IE([`string`,`string`,`float`],((e,t,n)=>ic(PE(e,`mix`),PE(t,`mix`),LE(n,`mix`,`percentage`,BE)/100).hex)),HE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},UE=IE([`string`],(e=>Hc(PE(e,`contrastOn`)).hex)),WE={depth:z.TRUECOLOR},GE=e=>IE([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uc(PE(t,`readableOn`),PE(n,`readableOn`),LE(r,`readableOn`,`ratio`,HE),i,void 0,a).hex})),KE={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function qE(){let e={};for(let[t,n]of Object.entries(KE)){let r=t;e[n]=IE([`string`,`float`],((e,t)=>{let i={...Sc,[r]:LE(t,n,`amount`)};return V.fromRgba(PE(e,n)).applyKey(i).toRgba().hex}))}return e}function JE(e=()=>WE){return{darken:RE,lighten:zE,mix:VE,contrastOn:UE,readableOn:GE(e),...qE()}}function YE(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:FE(Pc(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function XE(e){return{color:{fn:(t=>Pc(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new su(Jl(n),YE(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function ZE(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function QE(e){return{frames:{fn:((...t)=>um(new lm(ZE(`frame`,t,EE).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=ZE(`color`,t,e=>PE(e,`stepped`));return n[ru(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function $E(e){return{...NE(),...JE(e)}}new H({color:`red`,dim:!0});const eD=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,tD=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function nD(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(eD);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(tD);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function rD(e){let t=e.match(tD);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function iD(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function aD(e){return e.toLocaleString()}function oD(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function sD(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const cD=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],lD=cD.length;function uD(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(lD-1));o+=cD[t]}return o}function dD(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function fD(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const pD=jh(),mD=[...Qh];function hD(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>iD(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Tb(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>wb(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Eb(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>pD,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>mD,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(fD(`sparkline`,[`width`],n),uD(dD(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>sD(e,oD(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function gD(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>aD(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>nD(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>rD(e),argTypes:[`string`],arity:{kind:`exact`}}}}function _D(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return xS({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...uw(),...wE(),...Qw(),...bT(),...nw(t),...KS(),...Ew(),...ww(),...$E(n&&(()=>({depth:n()}))),...QE(()=>t().getTime()/1e3),...hD(),...gD(t),...r??{}}})}function vD(e){return yD(e,new Set(e.names()),``)}function yD(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?xD(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return yD(e,t,a)}})}function bD(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function xD(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new Db(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function SD(e){return p.existsSync(s.join(e,`.git`))}function CD(e){let t=s.resolve(e);for(;;){if(SD(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function wD(e){let t=CD(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function TD(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function ED(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const DD={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},OD={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function kD(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}function AD(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(jD(e,t))}function jD(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??MD(t.stderr)].filter(Boolean).join(`, `)}`}function MD(e){return e.trim().split(`
|
|
73
|
-
`,1)[0]??``}function
|
|
74
|
-
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function
|
|
75
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function
|
|
76
|
-
`).length:0)}async getRemotesAsync(e){let t=nO(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return HD(await this.execGitAsync(VD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=KD(e);return(n===null?null:JD(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=qD(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=BD(t);return n===`github`?ZD(`gh pr view`,await this.execForgeAsync(FD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,eO):n===`gitlab`?ZD(`glab mr view`,await this.execForgeAsync(FD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,tO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=AD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F($D(t.value)):t}};const iO=(e,t)=>D(t);var aO=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??iO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},oO=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const sO={showSha:!0,showStashCount:!0};function cO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function lO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function uO(e,t){return e.head!==t.head||e.index!==t.index}function dO(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}var fO=class extends rO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new oO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new rO,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new aO({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.entries.values())t.value.kind===`expired`&&e++;return{size:this.entries.size,expired:e,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${cO(t)}`,r=Date.now(),i=this.entries.get(n);if(i?.value.kind===`fresh`&&r-i.value.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(F(i.value.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=lO(i),o=await this.inner.getGitInfo(e,n);if(o.kind===`absent`&&this.dropRepo(e),o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch));let c={kind:`fresh`,info:s,computedAt:r,mtime:a},l=this.entries.get(t)??{value:c,watcher:this.watchers.acquire(`git:${e}`,dO(i),()=>this.invalidateRepo(e)),repoRoot:e};return l.value=c,this.entries.delete(t),this.entries.set(t,l),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return I;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,dO(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...sO});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let n of this.entries.values())n.repoRoot===e&&n.value.kind===`fresh`&&(n.value={kind:`expired`},t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} expired=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...sO}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}dropRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(this.dropEntry(n),t++);t>0&&this.logger(`info`,`gitCache drop ${e} entries=${t}`)}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){if(t.value.kind===`expired`)continue;let n=e.get(t.repoRoot);n||(n=lO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),uO(t.value.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const pO=/\r\n|\r|\n/g,mO=e=>F(e.replace(pO,` `).trim());function hO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(pO,` `))}}const gO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}},_O=e=>e.getTime()/1e3,vO=e=>new Date(e*1e3);function yO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function bO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const xO=`session.id`;function SO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function CO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function wO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const TO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],EO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],DO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],OO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function kO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>TO[e.getMonth()]],[`Monday`,e=>DO[e.getDay()]],[`Jan`,e=>EO[e.getMonth()]],[`Mon`,e=>OO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const AO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function jO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=AO[t];try{return zO(r,e)}catch{return BO(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function MO(e){try{return b(e)}catch{return e}}function NO(e){try{return ee(e).isDirectory()}catch{return!1}}function PO(e){let t=MO(e);return NO(t)?{dir:t,name:null,leaf:!0}:_b(t)}const FO=e=>`${e.dir}\0${e.name??``}`;var IO=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:PO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=PO(e);if(t.watcher!==null&&FO(n)===FO(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},LO=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function RO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function zO(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?wb(e):t===`number`?Tb(e):Eb(e)}function BO(e){return e===`number`?0:e===`boolean`?!1:``}var VO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new IO;ttlMgr=new LO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new oO;abort=new AbortController;drawn=xb.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=xb.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return vO(e)};engine=_D({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new fO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Cb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,SO(t,n.cwd,this.abort.signal),yO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,CO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,mO,t.default,n);case`regex`:return this.scalarPublisher(e,hO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=wO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=wO(s,gO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(vD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>kO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Ob(t)?new Db(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=AO[t.field],r=t.varDefault===void 0?BO(n):zO(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,jO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(xO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(xO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=RO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,zO(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(vD(this.store)).map(e=>e.plain).join(``))}catch(e){return Ob(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,xb.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,xb.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,zO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,BO(t))}}defaultFor(e){try{return zO(this.defaultEmptyValue,e)}catch{return BO(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function HO(e,t){let n=X_[e],r=iv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const UO=Object.fromEntries([...fv].map(([e,t])=>[t,HO(e,t)])),WO={subscribers:`number`,fps:`number`,shown:`boolean`},GO=Object.keys(WO),KO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[xO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...UO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(E_.flatMap(e=>GO.map(t=>[A_(e,t),{kind:`input`,path:A_(e,t),type:WO[t],default:k_[t]}]))),[O_(`by`)]:{kind:`input`,path:O_(`by`),default:D_.by},[O_(`fps`)]:{kind:`input`,path:O_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},qO=`ne .tmux.pane ""`;function JO(e,t,n){let r=new Set,i=e=>{for(let t of sb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of _g(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(xO);for(let t of Object.values(e.actions)){r.add(xO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?pv.get(t.set):void 0,n=`persist`in t?fv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function YO(e,t,n){let r=hb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of JO(e,t,n.helpers)){if(mb(a,r))continue;let e=KO[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function XO(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ZO=`groups.`,QO=`menus.`,$O=`edit.`,X=`candybar.`,ek=[ZO,QO,$O,X];function tk(e){return ek.some(t=>e.startsWith(t))}function nk(e){let t=XO(e);return ek.find(e=>t.startsWith(XO(e)))}function rk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function ik(e){return e}function ak(e,t,n){return n===void 0?QO+XO(e)+`.`+XO(t):ok(n)}function ok(e){return QO+XO(e)}function sk(e,t){return e+`.`+t}function ck(e){return e+`.page`}const lk=[`closeOnPick`,`paged`,`key`,`distribution`],uk=e=>lk.includes(e),dk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Am.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function fk(e){for(let t of Object.keys(e))if(!uk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${dk}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!jm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Am.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Nm(r)}}const pk=e=>`from`in e?e.from:e.themes;function mk(e,t,n){return e===`bool`?lg(t)!==null:`min`in e?ug(t,e)!==null:Ky(pk(e),n).members.includes(t)}function hk(e,t){if(e===`bool`)return sg.join(` or `);if(!(`min`in e)){let n=pk(e),{members:r}=Ky(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function gk(e){return{label:e.label,domain:_k(e.domain)}}function _k(e){return e===`theme`?{themes:Uy}:e===`bool`||`min`in e?e:{from:e}}function vk(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...sg]}},variables:{}};if(`from`in o)return yk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return yk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function yk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=sk(n,t),s=`${t}.open`,c=ck(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const bk=Object.fromEntries(Object.entries(X_).map(([e,t])=>[e,t.spec]));function xk(e){return X_[e].domain}function Sk(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function Ck(e){return Sk(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function wk(e){return Sk(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function Tk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Lh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Ek={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Dk={noun:`globals key`,fields:bk,removed:Ek},Ok={preset:Ck(`a preset`),menuGlyph:wk(`a preset`)},kk={noun:`preset globals key`,fields:{...bk,...Ok},removed:Ek};function Ak(e){return Bk(e)&&!(e in Ok)}const jk=`is decided later than any rule could be settled`,Mk={noun:`editGlobals key`,removed:Ek,fields:{...bk,preset:Ck(`the editGlobals fragment`),menuGlyph:wk(`the editGlobals fragment`),palette:Tk(bk.palette,`the editGlobals fragment`,jk),style:Tk(bk.style,`the editGlobals fragment`,jk),effect:Tk(bk.effect,`the editGlobals fragment`,jk)}},Nk={noun:`theme default key`,fields:{...Object.fromEntries(ev.map(e=>[e,bk[e]])),style:Tk(bk.style,`a theme's default`,`is the look that theme wears by name`)}};function Pk(e,t){if(!Qg(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${$g(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Oh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=e_(e,Nk,t,i);a!==null&&(n[r]=a)}return n}function Fk(e,t,n){return n===void 0?{}:e_(e,Dk,t,n)??{}}function Ik(e,t,n){return e_(e,kk,t,n)??{}}function Lk(){return x_(kk)}function Rk(e,t,n){return e_(e,Mk,t,n)??{}}const zk=new Set(Object.keys(bk));function Bk(e){return zk.has(e)}function Vk(e){return Object.hasOwn(Ek,e)?Ek[e]:void 0}function Hk(){return[...zk]}const Uk=new Map(Object.entries(X_).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Wk(e){let t=new Map;for(let[n,r]of Uk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Gk=/^segments\.([^.]+)\.palette$/,Kk=/^presets\.(.+)\.root$/,qk=/^presets\.(.+)\.globals\.([^.]+)$/,Jk=/^themeDefaults\.(.+)\.([^.]+)$/;function Yk(e){return`presets.${e}.root`}function Xk(e,t){return`themeDefaults.${e}.${t}`}const Zk=e=>ev.includes(e);function Qk(e,t){return`presets.${e}.globals.${t}`}function $k(e){if(Bk(e))return{scope:`globals`,field:e};let t=Gk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=qk.exec(e);if(n&&Ak(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=Jk.exec(e);if(r&&Zk(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Kk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function eA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const tA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],nA=[...tA,`other`],rA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},iA=xS({fromString:e=>e}),aA=`edit.mode`,oA=`edit.configure`,sA=`edit.toggle`,cA=`edit.unconfigure`,lA=[sA,cA],uA=`arrange`,dA=`${$O}draft.`;function fA(e,t){return`${e}:${t}`}const pA={variable:aA,key:aA,member:uA},mA=$r(pA);function hA(e){try{return iA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function gA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&hA(e))return!0;return!1}function _A(e,t){if(rk(e,t,$O,`edit mode`),!gA(t))return;let{variables:n,actions:r}=vA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function vA(){return{variables:{[aA]:ii(aA,P),[oA]:ii(oA,P)},actions:{[sA]:ai(aA,uA),[cA]:{set:oA,to:P}}}}const yA=`open`;function bA(e,t,n,r){let i={variable:e,key:e,member:yA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,yA),r.segments[e]={template:ti(e,`(?)`,`✕`),...xA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function xA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const SA=`none`;function CA(e){return Pc(e,`background`)}var wA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function TA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=EA(n,i),l=c!==SA,u=l?c===void 0?o:DA(a,c,`bg`):CA(a);e.bg=u;let d=EA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:DA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function EA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function DA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new wA(t,n,e.message):e}}const OA=`🔧`,kA={help:[`-h`,`--help`],version:[`-V`,`--version`]},AA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],jA=Object.fromEntries(AA.map(e=>[e.member,e.label])),MA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},NA=Object.keys(MA),PA=mv(e=>sv[e].place),FA=e=>Object.hasOwn(MA,e),IA=(e,t)=>e===t||FA(e)&&IA(PA[MA[e].beside],t),LA=e=>FA(e)?`${LA(PA[MA[e].beside])} › ${MA[e].trigger}`:e===`door`?`first line`:jA[e],RA=e=>LA(PA[e]),zA=()=>[`door`,...AA.map(e=>e.member)].flatMap(e=>[e,...NA.filter(t=>IA(t,e))]).map(e=>({path:LA(e),names:cv.filter(t=>PA[t]===e)})).filter(({names:e})=>e.length>0),BA=e=>`${T_[e].label} is off — turn it on in the settings menu's ${RA(T_[e].setting)}, or set globals.${T_[e].setting}: true`,VA=[...new Set(Object.values(T_).map(e=>RA(e.setting)))].join(` or `),HA=Math.max(...Object.values(sv).map(e=>e.configKey.length))+2,UA=[`✚ inserts`,`✖ removes`,`${OA} configures`,`↺ resets layout`],WA={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},GA=`
|
|
70
|
+
`)}function ZT(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function QT(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Bw(`join`,2,`list of strings/primitives`,`list element of type ${$T(e)}`);n.push(String(e))}return n.join(e)}function $T(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function eE(e){return UT(e,`-`)}function tE(e){return e.toLowerCase()}function nE(e,t){return`\n${XT(e,t)}`}function rE(e){return e.replace(/\s+/g,``)}function iE(e,t,n){return n===1?e:t}function aE(...e){return e.map(e=>`"${e}"`).join(` `)}function oE(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function sE(e,t){return t.repeat(Math.max(0,e))}function cE(e,t,n){return OT(e,n).join(t)}function lE(e){return UT(e,`_`)}function uE(e,t){let n=OT(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function dE(e,t){return OT(e,t)}function fE(e,t,n){let r=pE(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function pE(e,t,n){if(n===0)return[];let r=OT(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function mE(...e){return e.map(e=>`'${e}'`).join(` `)}function hE(e,t,n){let r=DT(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function gE(e){let t=``;for(let n of e)_E(n)?t+=n.toLowerCase():vE(n)?t+=n.toUpperCase():t+=n;return t}function _E(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function vE(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function yE(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function bE(e){return e.trim()}function xE(e,t){if(e.length===0)return t;let n=new Set(DT(e)),r=DT(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function SE(e,t){return t.startsWith(e)?t.slice(e.length):t}function CE(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function wE(e,t){let n=DT(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function TE(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function EE(e){return e.toUpperCase()}function DE(e,t){return OE(e,`
|
|
71
|
+
`,t)}function OE(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
72
|
+
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function kE(e,t,n){return OE(e,t,n)}function AE(){return{abbrev:{fn:(e,t)=>kT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>AT(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>GT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>KT(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>qT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>JT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>YT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>XT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>ZT(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>QT(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>eE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>tE(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>nE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>rE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>iE(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>aE(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>oE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>sE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>cE(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>lE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>uE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>dE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>fE(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>mE(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>hE(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>gE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>yE(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>bE(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>xE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>SE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>CE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>wE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>TE(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>EE(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>DE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>kE(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function jE(e,t){let n=ME(e),r=n.copy();return r.style=Su(n.style,t),r}function ME(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function NE(e){return{fn:(t=>jE(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function PE(e){return{fn:((t,n)=>jE(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function FE(e,t){return new H({[e]:t})}function IE(){let e={};for(let t of gu)e[t]=NE(FE(t,!0)),e[`not_${t}`]=NE(FE(t,!1));for(let[t,n]of Object.entries(vu))e[t]=NE(FE(n,!0));return e}const LE={fn:((e,t)=>jE(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},RE={fn:((e,t)=>jE(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function zE(){return{fg:PE(`color`),bg:PE(`bgcolor`),...IE(),link:RE,style:LE}}function BE(e,t){let n;try{n=rc(e.trim())}catch(n){throw n instanceof zs?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return VE(n,t,JSON.stringify(e))}function VE(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function HE(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function UE(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const WE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`darken`),t).hex)),GE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`lighten`),-t).hex)),KE={min:0,max:100,note:`0 = from, 100 = toward`},qE=HE([`string`,`string`,`float`],((e,t,n)=>ic(BE(e,`mix`),BE(t,`mix`),UE(n,`mix`,`percentage`,KE)/100).hex)),JE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},YE=HE([`string`],(e=>Hc(BE(e,`contrastOn`)).hex)),XE={depth:z.TRUECOLOR},ZE=e=>HE([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uc(BE(t,`readableOn`),BE(n,`readableOn`),UE(r,`readableOn`,`ratio`,JE),i,void 0,a).hex})),QE={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function $E(){let e={};for(let[t,n]of Object.entries(QE)){let r=t;e[n]=HE([`string`,`float`],((e,t)=>{let i={...Sc,[r]:UE(t,n,`amount`)};return V.fromRgba(BE(e,n)).applyKey(i).toRgba().hex}))}return e}function eD(e=()=>XE){return{darken:WE,lighten:GE,mix:qE,contrastOn:YE,readableOn:ZE(e),...$E()}}function tD(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:VE(Pc(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function nD(e){return{color:{fn:(t=>Pc(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new su(Jl(n),tD(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function rD(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function iD(e){return{frames:{fn:((...t)=>dm(new um(rD(`frame`,t,ME).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=rD(`color`,t,e=>BE(e,`stepped`));return n[ru(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function aD(e){return{...zE(),...eD(e)}}new H({color:`red`,dim:!0});const oD=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,sD=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function cD(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(oD);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(sD);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function lD(e){let t=e.match(sD);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function uD(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function dD(e){return e.toLocaleString()}function fD(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function pD(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const mD=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hD=mD.length;function gD(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(hD-1));o+=mD[t]}return o}function _D(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function vD(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const yD=Lh(),bD=[...ig];function xD(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>uD(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(jb(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Ab(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Mb(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>yD,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>bD,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(vD(`sparkline`,[`width`],n),gD(_D(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>pD(e,fD(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function SD(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>dD(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>cD(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>lD(e),argTypes:[`string`],arity:{kind:`exact`}}}}function CD(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return DS({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...gw(),...AE(),...iT(),...ET(),...cw(t),...QS(),...Mw(),...Aw(),...aD(n&&(()=>({depth:n()}))),...iD(()=>t().getTime()/1e3),...xD(),...SD(t),...r??{}}})}function wD(e){return TD(e,new Set(e.names()),``)}function TD(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?DD(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return TD(e,t,a)}})}function ED(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function DD(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new Nb(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function OD(e){return p.existsSync(s.join(e,`.git`))}function kD(e){let t=s.resolve(e);for(;;){if(OD(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function AD(e){let t=kD(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function jD(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function MD(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const ND={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},PD={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function FD(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}function ID(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(LD(e,t))}function LD(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??RD(t.stderr)].filter(Boolean).join(`, `)}`}function RD(e){return e.trim().split(`
|
|
73
|
+
`,1)[0]??``}function zD(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function BD(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const VD={github:`gh`,gitlab:`glab`};function HD(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const UD=/^[A-Za-z]:[\\/]/;function WD(e){let t=e.trim();if(UD.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function GD(e){return WD(e)?.host||null}function KD(e){let t=GD(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const qD=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function JD(e){let t=ID(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?YD(t.value):[]}}function YD(e){let t=new Map;for(let n of e.split(`
|
|
74
|
+
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function XD(e){return e.urls.find(e=>tO(e)!==null)??e.urls[0]??null}function ZD(e){return e.find(e=>e.name===`origin`)??e[0]??null}function QD(e){let t=ZD(e);return t?XD(t):null}function $D(e){let t=ZD(e);return t?t.urls.find(e=>KD(e)!==null)??XD(t):null}function eO(e){let t=(WD(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function tO(e){let t=WD(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function nO(e){let t=QD(e);return t===null?null:tO(t)}function rO(e,t,n,r){return t.ok?r(t.stdout):HD(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??RD(t.stderr)].filter(Boolean).join(`, `)}`)}function iO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aO(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
75
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function oO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!iO(t))return L(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`);let o=FD(`gh pr view`,ND,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function sO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!iO(t))return L(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`);let o=FD(`glab mr view`,PD,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function cO(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var lO=class{isGitRepo(e){return OD(e)}async execGitAsync(e,t){return lt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}async findGitRoot(e){let t=kD(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=await this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=zD(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=zD(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=zD(s,nO)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?F(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return BD(ID(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestampMs(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestampMs(e,t){let n=BD(ID(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10)*1e3;return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`):F(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return F(r?r.split(`
|
|
76
|
+
`).length:0)}async getRemotesAsync(e){let t=cO(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return JD(await this.execGitAsync(qD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=QD(e);return(n===null?null:eO(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=$D(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=KD(t);return n===`github`?rO(`gh pr view`,await this.execForgeAsync(VD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,oO):n===`gitlab`?rO(`glab mr view`,await this.execForgeAsync(VD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,sO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=ID(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(aO(t.value)):t}};const uO=(e,t)=>D(t);var dO=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??uO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},fO=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const pO={showSha:!0,showStashCount:!0};function mO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function hO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function gO(e,t){return e.head!==t.head||e.index!==t.index}function _O(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}var vO=class extends lO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new fO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new lO,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new dO({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.entries.values())t.value.kind===`expired`&&e++;return{size:this.entries.size,expired:e,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${mO(t)}`,r=Date.now(),i=this.entries.get(n);if(i?.value.kind===`fresh`&&r-i.value.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(F(i.value.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=hO(i),o=await this.inner.getGitInfo(e,n);if(o.kind===`absent`&&this.dropRepo(e),o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch));let c={kind:`fresh`,info:s,computedAt:r,mtime:a},l=this.entries.get(t)??{value:c,watcher:this.watchers.acquire(`git:${e}`,_O(i),()=>this.invalidateRepo(e)),repoRoot:e};return l.value=c,this.entries.delete(t),this.entries.set(t,l),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return I;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,_O(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...pO});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let n of this.entries.values())n.repoRoot===e&&n.value.kind===`fresh`&&(n.value={kind:`expired`},t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} expired=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...pO}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}dropRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(this.dropEntry(n),t++);t>0&&this.logger(`info`,`gitCache drop ${e} entries=${t}`)}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){if(t.value.kind===`expired`)continue;let n=e.get(t.repoRoot);n||(n=hO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),gO(t.value.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const yO=/\r\n|\r|\n/g,bO=e=>F(e.replace(yO,` `).trim());function xO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(yO,` `))}}const SO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}},CO=e=>e.getTime()/1e3,wO=e=>new Date(e*1e3);function TO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function EO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const DO=`session.id`;function OO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function kO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function AO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const jO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],MO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],NO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],PO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function FO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>jO[e.getMonth()]],[`Monday`,e=>NO[e.getDay()]],[`Jan`,e=>MO[e.getMonth()]],[`Mon`,e=>PO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const IO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function LO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=IO[t];try{return GO(r,e)}catch{return KO(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function RO(e){try{return b(e)}catch{return e}}function zO(e){try{return ee(e).isDirectory()}catch{return!1}}function BO(e){let t=RO(e);return zO(t)?{dir:t,name:null,leaf:!0}:Cb(t)}const VO=e=>`${e.dir}\0${e.name??``}`;var HO=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:BO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=BO(e);if(t.watcher!==null&&VO(n)===VO(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},UO=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GO(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Ab(e):t===`number`?jb(e):Mb(e)}function KO(e){return e===`number`?0:e===`boolean`?!1:``}var qO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new HO;ttlMgr=new UO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fO;abort=new AbortController;drawn=Db.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=Db.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return wO(e)};engine=CD({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new vO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,kb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,OO(t,n.cwd,this.abort.signal),TO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,kO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,bO,t.default,n);case`regex`:return this.scalarPublisher(e,xO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=AO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=AO(s,SO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(wD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>FO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Pb(t)?new Nb(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=IO[t.field],r=t.varDefault===void 0?KO(n):GO(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,LO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(DO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(DO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GO(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(wD(this.store)).map(e=>e.plain).join(``))}catch(e){return Pb(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,Db.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,Db.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KO(t))}}defaultFor(e){try{return GO(this.defaultEmptyValue,e)}catch{return KO(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function JO(e,t){let n=nv[e],r=uv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const YO=Object.fromEntries([...vv].map(([e,t])=>[t,JO(e,t)])),XO={subscribers:`number`,fps:`number`,shown:`boolean`},ZO=Object.keys(XO),QO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[DO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...YO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(M_.flatMap(e=>ZO.map(t=>[I_(e,t),{kind:`input`,path:I_(e,t),type:XO[t],default:F_[t]}]))),[P_(`by`)]:{kind:`input`,path:P_(`by`),default:N_.by},[P_(`fps`)]:{kind:`input`,path:P_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},$O=`ne .tmux.pane ""`;function ek(e,t,n){let r=new Set,i=e=>{for(let t of pb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of Cg(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(DO);for(let t of Object.values(e.actions)){r.add(DO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?yv.get(t.set):void 0,n=`persist`in t?vv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function tk(e,t,n){let r=xb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of ek(e,t,n.helpers)){if(bb(a,r))continue;let e=QO[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function nk(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const rk=`groups.`,ik=`menus.`,ak=`edit.`,X=`candybar.`,ok=[rk,ik,ak,X];function sk(e){return ok.some(t=>e.startsWith(t))}function ck(e){let t=nk(e);return ok.find(e=>t.startsWith(nk(e)))}function lk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function uk(e){return e}function dk(e,t,n){return n===void 0?ik+nk(e)+`.`+nk(t):fk(n)}function fk(e){return ik+nk(e)}function pk(e,t){return e+`.`+t}function mk(e){return e+`.page`}const hk=[`closeOnPick`,`paged`,`key`,`distribution`],gk=e=>hk.includes(e),_k=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${jm.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function vk(e){for(let t of Object.keys(e))if(!gk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${_k}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Mm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${jm.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Pm(r)}}const yk=e=>`from`in e?e.from:e.themes;function bk(e,t,n){return e===`bool`?hg(t)!==null:`min`in e?gg(t,e)!==null:Qy(yk(e),n).members.includes(t)}function xk(e,t){if(e===`bool`)return pg.join(` or `);if(!(`min`in e)){let n=yk(e),{members:r}=Qy(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function Sk(e){return{label:e.label,domain:Ck(e.domain)}}function Ck(e){return e===`theme`?{themes:Yy}:e===`bool`||`min`in e?e:{from:e}}function wk(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...pg]}},variables:{}};if(`from`in o)return Tk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return Tk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function Tk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=pk(n,t),s=`${t}.open`,c=mk(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const Ek=Object.fromEntries(Object.entries(nv).map(([e,t])=>[e,t.spec]));function Dk(e){return nv[e].domain}function Ok(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function kk(e){return Ok(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function Ak(e){return Ok(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function jk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Uh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Mk={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Nk={noun:`globals key`,fields:Ek,removed:Mk},Pk={preset:kk(`a preset`),menuGlyph:Ak(`a preset`)},Fk={noun:`preset globals key`,fields:{...Ek,...Pk},removed:Mk};function Ik(e){return Kk(e)&&!(e in Pk)}const Lk=`is decided later than any rule could be settled`,Rk={noun:`editGlobals key`,removed:Mk,fields:{...Ek,preset:kk(`the editGlobals fragment`),menuGlyph:Ak(`the editGlobals fragment`),palette:jk(Ek.palette,`the editGlobals fragment`,Lk),style:jk(Ek.style,`the editGlobals fragment`,Lk),effect:jk(Ek.effect,`the editGlobals fragment`,Lk)}},zk={noun:`theme default key`,fields:{...Object.fromEntries(ov.map(e=>[e,Ek[e]])),style:jk(Ek.style,`a theme's default`,`is the look that theme wears by name`)}};function Bk(e,t){if(!i_(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${a_(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Ph(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=o_(e,zk,t,i);a!==null&&(n[r]=a)}return n}function Vk(e,t,n){return n===void 0?{}:o_(e,Nk,t,n)??{}}function Hk(e,t,n){return o_(e,Fk,t,n)??{}}function Uk(){return D_(Fk)}function Wk(e,t,n){return o_(e,Rk,t,n)??{}}const Gk=new Set(Object.keys(Ek));function Kk(e){return Gk.has(e)}function qk(e){return Object.hasOwn(Mk,e)?Mk[e]:void 0}function Jk(){return[...Gk]}const Yk=new Map(Object.entries(nv).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Xk(e){let t=new Map;for(let[n,r]of Yk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Zk=/^segments\.([^.]+)\.palette$/,Qk=/^presets\.(.+)\.root$/,$k=/^presets\.(.+)\.globals\.([^.]+)$/,eA=/^themeDefaults\.(.+)\.([^.]+)$/;function tA(e){return`presets.${e}.root`}function nA(e,t){return`themeDefaults.${e}.${t}`}const rA=e=>ov.includes(e);function iA(e,t){return`presets.${e}.globals.${t}`}function aA(e){if(Kk(e))return{scope:`globals`,field:e};let t=Zk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=$k.exec(e);if(n&&Ik(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=eA.exec(e);if(r&&rA(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Qk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function oA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const sA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],cA=[...sA,`other`],lA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},uA=DS({fromString:e=>e}),dA=`edit.mode`,fA=`edit.configure`,pA=`edit.toggle`,mA=`edit.unconfigure`,hA=[pA,mA],gA=`arrange`,_A=`${ak}draft.`;function vA(e,t){return`${e}:${t}`}const yA={variable:dA,key:dA,member:gA},bA=$r(yA);function xA(e){try{return uA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function SA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&xA(e))return!0;return!1}function CA(e,t){if(lk(e,t,ak,`edit mode`),!SA(t))return;let{variables:n,actions:r}=wA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function wA(){return{variables:{[dA]:ii(dA,P),[fA]:ii(fA,P)},actions:{[pA]:ai(dA,gA),[mA]:{set:fA,to:P}}}}const TA=`open`;function EA(e,t,n,r){let i={variable:e,key:e,member:TA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,TA),r.segments[e]={template:ti(e,`(?)`,`✕`),...DA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function DA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const OA=`none`;function kA(e){return Pc(e,`background`)}var AA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function jA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=MA(n,i),l=c!==OA,u=l?c===void 0?o:NA(a,c,`bg`):kA(a);e.bg=u;let d=MA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:NA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function MA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function NA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new AA(t,n,e.message):e}}const PA=`🔧`,FA={help:[`-h`,`--help`],version:[`-V`,`--version`]},IA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],LA=Object.fromEntries(IA.map(e=>[e.member,e.label])),RA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},zA=Object.keys(RA),BA=bv(e=>pv[e].place),VA=e=>Object.hasOwn(RA,e),HA=(e,t)=>e===t||VA(e)&&HA(BA[RA[e].beside],t),UA=e=>VA(e)?`${UA(BA[RA[e].beside])} › ${RA[e].trigger}`:e===`door`?`first line`:LA[e],WA=e=>UA(BA[e]),GA=()=>[`door`,...IA.map(e=>e.member)].flatMap(e=>[e,...zA.filter(t=>HA(t,e))]).map(e=>({path:UA(e),names:mv.filter(t=>BA[t]===e)})).filter(({names:e})=>e.length>0),KA=e=>`${j_[e].label} is off — turn it on in the settings menu's ${WA(j_[e].setting)}, or set globals.${j_[e].setting}: true`,qA=[...new Set(Object.values(j_).map(e=>WA(e.setting)))].join(` or `),JA=Math.max(...Object.values(pv).map(e=>e.configKey.length))+2,YA=[`✚ inserts`,`✖ removes`,`${PA} configures`,`↺ resets layout`],XA={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},ZA=`
|
|
77
77
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
78
78
|
|
|
79
79
|
Usage: cc-candybar [options]
|
|
80
80
|
|
|
81
81
|
Standalone Commands:
|
|
82
|
-
${
|
|
83
|
-
${
|
|
82
|
+
${FA.help.join(`, `).padEnd(25)}Show this help
|
|
83
|
+
${FA.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
|
|
84
84
|
|
|
85
85
|
Debugging:
|
|
86
86
|
CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
|
|
@@ -97,21 +97,21 @@ Configuration:
|
|
|
97
97
|
the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
|
|
98
98
|
and 💾 save, which appears while you have unsaved changes and writes them to
|
|
99
99
|
your config file. Under it are its
|
|
100
|
-
tabs, ${
|
|
101
|
-
${
|
|
100
|
+
tabs, ${IA.map(e=>e.label).join(`, `)};
|
|
101
|
+
${LA.session} holds quick actions and commands, ${LA.layout} a new preset.
|
|
102
102
|
A change applies to this session at once.
|
|
103
103
|
Where each setting is in the menu: the globals field that sets it in a
|
|
104
104
|
config file, then the control's label.
|
|
105
|
-
${
|
|
105
|
+
${GA().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${pv[e].configKey.padEnd(JA)}${pv[e].label}`)]).join(`
|
|
106
106
|
`)}
|
|
107
107
|
The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
|
|
108
108
|
failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
|
|
109
109
|
|
|
110
110
|
Anywhere the bar shows (?), clicking it reveals these same instructions
|
|
111
|
-
in place. In edit mode: ${
|
|
111
|
+
in place. In edit mode: ${YA.join(`, `)}.
|
|
112
112
|
|
|
113
|
-
Animation lanes (experimental; toggles in the settings menu's ${
|
|
114
|
-
${
|
|
113
|
+
Animation lanes (experimental; toggles in the settings menu's ${qA}):
|
|
114
|
+
${M_.map(e=>` ${j_[e].label}\n${XA[e].map(e=>` ${e}`).join(`
|
|
115
115
|
`)}`).join(`
|
|
116
116
|
`)}
|
|
117
117
|
|
|
@@ -142,17 +142,17 @@ Subcommands:
|
|
|
142
142
|
Claude Code's statusline JSON from stdin (one object
|
|
143
143
|
a line) and sends it as the session's data
|
|
144
144
|
(--config rides with it). LANE is one of
|
|
145
|
-
${
|
|
145
|
+
${M_.join(`, `)}:
|
|
146
146
|
the experimental lane this stream serves,
|
|
147
147
|
which streams only while its toggle in the settings
|
|
148
|
-
menu's ${
|
|
148
|
+
menu's ${qA} is on.
|
|
149
149
|
bar-pane PANE Draw the bar of the Claude Code session in tmux
|
|
150
150
|
pane PANE (e.g. %3) in this pane, as the daemon
|
|
151
151
|
pushes it, while this pane is shown. The bar is
|
|
152
152
|
drawn at PANE's width, so split PANE with -v for a
|
|
153
153
|
pane under it that fits. Experimental:
|
|
154
|
-
runs while ${
|
|
155
|
-
menu's ${
|
|
154
|
+
runs while ${j_.pane.label} is on in the settings
|
|
155
|
+
menu's ${WA(j_.pane.setting)}.
|
|
156
156
|
|
|
157
157
|
Config tooling:
|
|
158
158
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -178,17 +178,17 @@ Config tooling:
|
|
|
178
178
|
config [--json] The effective merged config. (All three query the
|
|
179
179
|
running daemon; none spawn one.)
|
|
180
180
|
|
|
181
|
-
`,
|
|
182
|
-
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return jj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${Lj[e]}`)])}}},zj="re-run `cc-candybar install`";function Bj(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${zj}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${zj}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${zj}`)}const Vj={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${zj}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${zj}`};case`lost`:return jj([...Bj(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function Hj({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function Uj(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${E_.join(`|`)}>\``:e.checkout===null?zj:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Wj(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${Uj(e,`native`)}`];let{bundle:i,source:a}=Hj(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${Uj(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${Uj(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const Gj=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},Kj={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${Gj(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:jj([...new Set(i.flatMap(e=>Wj(n,r,e)))])}};function qj({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function Jj(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Yj={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?Jj(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return jj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=qj(e.value,n),u=jj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${Nn(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Rn(o.charge.bytes,s)?[`the daemon holds ${Hn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},Xj=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Zj(e,t){let n=vj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?bj(e.terminal):{kind:`unknown`}}function Qj({identified:e,tmuxClient:t},n){let r=yj(e),i=Zj(e,n),a=vj(e)===null?Xj:`${Xj}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${xj}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const $j={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return jj(Qj(t,n))}}},eM=e=>e.filter(e=>e.role===`statusline`),tM={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>iM(e,nM(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:rM(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:Gj(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},nM=e=>{let t=eM(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},rM=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function iM(e,t){let n=Sj(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return rM(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return Tj(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const aM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function oM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return yj(e);case`bundling`:case`unread`:case`configured`:return[cj(e.name),e.version].filter(e=>e!==null).join(` `)}}function sM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return vj(e);case`bundling`:case`unread`:return cj(e.name);case`configured`:{let t=cj(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function cM(e){let t=sM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${aM(e.glyphs)}`}}const lM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=cM(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=oM(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${aM(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=ij[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:pj(i.version,e);if(t===!0)return{ok:!0};let n=cj(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${aM(n)} — set a Nerd Font as its font`)}}}};function uM(e){return e.join(`, `)}function dM(e){return`or set missingData: "ignore" on ${uM(e)}`}function fM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${uM(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${uM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${dM(t)}`]:[`${uM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${dM(t)}`]}function pM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${uM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${uM(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${uM(n)}: ${Gj(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${uM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${uM(n)}`]:[]}function mM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${uM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${dM(t)}`];case`failed`:return[`${uM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const hM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>jj([...fM(e.pullRequests),...pM(e.rateLimits,t),...mM(e.memento)])};function gM({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${Oj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const _M=[Rj,Kj,Yj,Vj,$j,Pj,Fj,Ij,tM,lM,hM,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${Gj(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:jj(e.value.flatMap(gM))}],vM=_M.filter(e=>e.takesMark);function yM(e){return _M.map(t=>({check:t,verdict:t.probe(e)}))}function bM(e){return _M.find(t=>t.name===e)}const xM=/^[^\s"=\\]+$/,SM=e=>xM.test(e)?e:JSON.stringify(e),CM=`${X}doctor.`;function wM(e){let t=`${CM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function TM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?vj(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function EM(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function DM(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=Hj(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const OM=e=>`${e>=0?`+`:``}${Nn(e)}`;function kM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${Jj(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${qj(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Un(i.charge)}${i.charge.kind===`stand-in`?`(${OM(-i.charge.gap)})`:``}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function AM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function jM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>MM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${SM(i)}`;let a=eM(r.flatMap(e=>e.bars));return`frames=${ej.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${SM(i)}`}function MM(e){let t=Sj(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function NM(e){let t=Cj(e,Mj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${SM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function PM(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function FM(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=cM(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function IM(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function LM(e){return e.flatMap(({check:e,verdict:t})=>{let n=wM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:og},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:IM(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?og:ag},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const RM={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function zM(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(RM).map(([t,n])=>[`${e}${t}`,n]))}}const BM=`armed`,VM=`disarmed`,HM=`.armed`,UM=e=>e.endsWith(HM);function WM(e,t,n){let r=`${e}${HM}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${BM}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:BM},[a]:{set:r,to:VM},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:VM}},disarm:a}}const GM=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function KM(e){return typeof e==`string`&&GM.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function qM(e){let t=KM(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const JM=[`/compact`,`/model`],YM=`/clear`;function XM(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=WM(`${e}clear`,{arm:YM,confirm:`${YM} ✓ confirm`},[n]);return{template:JM.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${qO} }}`,actions:{...Object.fromEntries(JM.map(e=>[t(e),{slash:qM(e)}])),...r.actions,[n]:{slash:qM(YM)}},variables:r.variables,disarm:r.disarm}}const ZM=Array.from({length:10},(e,t)=>(t+1)*1e5),QM=ZM[0],$M=ZM[ZM.length-1];function eN(e){let t;try{t=Da(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=QM&&n<=$M?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${QM}–${$M} tokens)`)}function tN(e,t){let n=Math.min(t??$M,$M),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:ZM.filter(e=>e<r).at(-1)??0,higher:ZM.find(e=>e>r&&e<=n)??0}}function nN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${qO} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:qM(`/autocompact auto`)},...Object.fromEntries(ZM.map(t=>[`${e}${t}`,{slash:qM(`/autocompact ${t}`)}]))}}}const rN=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,iN=`${X}menu`,aN=`open`,oN=`${X}edit`,sN=`${X}toolbar`,cN=zM(X),lN=`${X}commands`,uN=XM(`${lN}.`),dN=`${X}autocompact`,fN=nN(`${dN}.`,rN),pN=e=>({kind:`segment`,name:e}),mN=`${X}tab`,hN=e=>`${mN}.${e}`,gN=e=>`${hN(e)}.toggle`,_N=e=>({variable:mN,key:mN,member:e}),vN=`${X}save`,yN=`${X}preset.save`,bN=`${X}preset.delete`,xN=e=>`${X}${e}`,SN=e=>`${X}apply.${e}`,CN=e=>`${X}reset.${e}`,wN=`${X}themeDefault.save`,TN=`${X}themeDefault.differs`,EN=`${X}themeDefault.theme`,DN={when:`{{ .${TN} }}`,template:`{{ action "${wN}" (printf "⤓ default for %s" .${EN}) }} {{ swatch "${SN(`theme`)}" .${EN} }}`},ON=`${X}resetAll`,kN=`${iN}.toggle`,AN={variable:iN,key:iN,member:aN},jN=`${X}undo`,MN=`${X}back`,NN=`${MN}.step`,PN=`${X}navigation.back`,FN=MN,IN={template:`{{ if gt .${PN} 0 }}{{ action "${MN}" "◁" }}{{ else }}{{ fg (${KA}) "◁" }}{{ end }}`},LN=`${X}redo`,RN=`${X}doctor`,zN=`${RN}.run`,BN=e=>`${RN}.fix.${e}`,VN=(e,t)=>`${RN}.mark.${e}.${t}`,HN=e=>`${RN}.${e}`,UN={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},WN=ok(`${X}pickers`),GN=e=>`${X}${e}`,KN=e=>`${GN(e)}.toggle`,qN=e=>FA(e)?ok(`${X}${e}Pickers`):WN,JN=e=>{let t=qN(PA[MA[e].beside]);return{variable:t,key:t,member:e}},YN={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${bN}" (printf "🚮 delete %s" .${sv.preset.effectiveVar}) }}`}},XN=(e,t)=>`${X}list.${e}.${t}`,ZN=e=>`${X}resettable.${e}`,QN=e=>e.length===0?`false`:`(or ${e.map(e=>`.${ZN(e)}`).join(` `)})`,$N=E_.map(e=>[T_[e].setting,e]),eP={variables:{},actions:{},segments:{}},tP=Object.fromEntries($N.map(([e,t])=>[e,bA(`${X}help.${e}`,WA[t],[],eP)])),nP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],rP=e=>{let t=t=>`.${A_(e,t)}`,n=nP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${sv[T_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},iP=`{{ if eq .${O_(`by`)} "feed" }} {{ printf "%2d" (int .${O_(`fps`)}) }} fps{{ end }}`,aP=Object.fromEntries($N.map(([e,t])=>[e,rP(t)])),oP=Object.keys(sv).map(e=>{let t=sv[e],n=xk(t.configKey),r=vk({label:t.label,domain:n},t.sessionKey,t.effectiveVar,SN(e),qN(PA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>YN[e])}}),sP=e=>oP.filter(t=>PA[t.name]===e),cP=e=>oP.filter(t=>IA(PA[t.name],e)),lP=e=>t=>`(print ${ri(t)} (ternary ${ri(` •`)} "" ${QN(cP(e).map(e=>e.name))}))`,uP=e=>NA.filter(t=>MA[t].beside===e),dP=e=>sP(e).flatMap(e=>[CP(e),...[tP[e.name]].filter(e=>e!==void 0),...uP(e.name).map(e=>Qr(GN(e),JN(e),AP(e),`drop`))]);new Set(oP.flatMap(e=>[e.sessionKey,e.configKey]));const fP=WM(ON,{arm:`⟲`,confirm:`⟲ reset all?`},oP.map(e=>CN(e.name))),pP=[`unsaved`,`history.undo`,`history.redo`],mP=e=>`${X}${e}`,hP=mP(`unsaved`),gP=(e,t)=>({body:t,shown:`(gt .${mP(e)} 0)`}),_P=[gP(`unsaved`,`{{ action "${vN}" (printf "💾 save %d" .${hP}) }}`),gP(`history.undo`,`{{ action "${jN}" "↶" }}`),gP(`history.redo`,`{{ action "${LN}" "↷" }}`),{body:fP.template,shown:`(or ${QN(oP.map(e=>e.name))} ${fP.armed})`}],vP={when:`{{ or ${_P.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+_P.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},yP=[{step:fP,place:`door`},{step:uN,place:`session`}],bP=e=>e.map(e=>e.step.disarm),xP=bP(yP),SP=bP(yP.filter(e=>e.place!==`door`));function CP(e){let t=xN(e.name);return e.control.kind===`inline`?pN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>pN(XN(e.name,n)))},`drop`)}function wP(e){return e===iN}function TP(e){let t=pN(iN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[TP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function EP(e){return DP(e)>0?e:TP(e)}function DP(e){let t=0;for(let n of _g(e))n.kind===`segment`&&wP(n.name)&&(t+=1);return t}function OP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&wP(e.name)||e.opens!==void 0&&OP(e.opens.body,!0):e.children.some(e=>OP(e,n))}const kP={door:{direction:`horizontal`,content:[pN(FN)],after:[pN(oN),pN(vN)]},session:{direction:`vertical`,content:[pN(sN),{kind:`container`,direction:`horizontal`,children:[pN(lN),pN(dN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[pN(yN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[pN(RN),..._M.map(e=>pN(HN(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[pN(wN)]},toggles:{direction:`horizontal`,content:[],after:[]}};function AP(e){let{direction:t,content:n,after:r}=kP[e];return{kind:`container`,direction:t,children:[...n,...dP(e),...r]}}function jP(e){return e.kind===`segment`?wP(e.name)?Qr(e.name,AN,NP,`above`):e:FP(e)}function MP(){return{kind:`container`,direction:`vertical`,children:[AP(`door`),{kind:`container`,direction:`horizontal`,children:AA.map(({member:e})=>Qr(hN(e),_N(e),AP(e),`drop`))}]}}const NP=MP();function PP(e){let t=new Map;for(let e of _g(NP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${iN}.fold.${XO(t)}`;return e.actions[i]={set:t,to:r.default},i})}function FP(e){return{...e,children:e.children.map(e=>jP(e))}}function IP(e){let t={variables:{[iN]:ii(iN,P)},actions:{[kN]:ai(iN,aN),[zN]:{doctor:`run`},[oN]:{do:[...lA]},...cN.actions,...uN.actions,...fN.actions,[vN]:{save:!0},[jN]:{undo:!0},[NN]:{back:!0},[MN]:{do:[NN,...xP]},[LN]:{redo:!0},[yN]:{preset:`save`},[wN]:{themeDefault:`save`},[bN]:{preset:`delete`,name:`{{ .${sv.preset.effectiveVar} }}`}},segments:{[iN]:{template:`{{ $door := ${ni(iN,ri(e),ri(`✖`))} }}{{ if ${ei(AN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+iP},[sN]:{template:cN.template},[lN]:{template:uN.template,when:uN.when},[dN]:{template:fN.template,bg:fN.bg,when:fN.when},[FN]:IN,[vN]:vP,[wN]:DN,[yN]:{template:`{{ action "${yN}" "+ preset" }}`},[RN]:{template:`{{ action "${zN}" "🩺 doctor" }}`},[oN]:{template:`{{ action "${oN}" "✎ arrange" "✎ done" }}`}}};t.variables[TN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[EN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[PN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of pP)t.variables[mP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[mN]=ii(mN,`session`);for(let{member:e,label:n}of AA){t.actions[gN(e)]=ai(mN,e),t.actions[hN(e)]={do:[gN(e),...SP]};let r=lP(e);t.segments[hN(e)]={template:`{{ ${ni(hN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,uN.variables,fP.variables),RP(t),LP(t),t.actions[iN]={do:[kN,...xP,...PP(t)]},t}function LP(e){for(let t of _M){let n=wM(t.name),r=BN(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?Dj:[];for(let n of i)e.actions[VN(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${VN(t.name,e)}" "${UN[e]}" }}`).join(``);e.segments[HN(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${ag}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function RP(e){for(let t of oP){Object.assign(e.actions,t.control.actions);let n=CN(t.name);e.actions[n]={reset:t.configKey},e.variables[ZN(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${ZN(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[xN(t.name)]={template:`${t.control.template}${aP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[XN(t.name,r)]=n})}Object.assign(e.actions,fP.actions),Object.assign(e.variables,eP.variables),Object.assign(e.actions,eP.actions),Object.assign(e.segments,eP.segments);for(let t of NA){let n=JN(t);e.actions[KN(t)]=ai(n.key,n.member),e.segments[GN(t)]={template:`{{ action "${KN(t)}" ${lP(t)(MA[t].trigger)} }}`}}}function zP(e){let{variables:t,actions:n}=vA();Object.assign(e.variables,t),Object.assign(e.actions,n)}function BP(e){let t=IP(e.globals.menuGlyph??`🍫`);zP(t);let n={...e.presets},r=[];for(let t of Iy(e.presets)){let{node:i}=zy(e,t),a=jP(EP(i));r.push(a),n[t]={...Ry(e.presets,t),root:a}}let i=YO(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const VP=`${$O}live`,HP=[`☐ live`,`☑ live`],UP=`${$O}done`,WP=`${$O}cancel`,GP=`${$O}rewind`,KP=`${$O}changes`,qP=`(gt .${KP} 0)`,JP=`(or ${qP} (gt .${hP} 0))`,YP={variable:VP,key:VP,member:`open`};function XP(e){return`${$O}configuring.p${e}`}function ZP(e){return`and ${ei(pA)} (not ${ei(YP)}) (ne .${XP(e)} "true")`}function QP(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${oA} "${Zr(e)}")`).join(` `)} false }}`}}function $P(e,t,n){return`{{ if ${ZP(e)} }}${t}{{ else }}${n}{{ end }}`}const eF=`{{ and ${ei(pA)} .preset.customized }}`,tF=tk;function nF(e){return new Map([...Wy(e),...iF(e)])}const rF=`${$O}addable`;function iF(e){return new Map([[rF,{members:Object.keys(e.segments).filter(e=>!tF(e)),library:{groups:nA.map(e=>({id:e,label:rA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function aF(e,t,n){return n.segments[e]={template:t,when:mA,bg:SA},{kind:`segment`,name:e}}function oF(e,t,n){let r=`${$O}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${eh}`}) (action "${r}" "✖") }}`}function sF(e){return`{{ if ${ei(pA)} }}${e}{{ end }}`}function cF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(pA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function lF(e){return e.flatMap(e=>[..._g(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function uF(e,t,n){return`${dA}${e}.${t}.${n}`}function dF(e,t,n,r){let i=pg(n),a=`${$O}${e.presetIdent}`,o=fA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=ok(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:oA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=uF(e.presetIdent,i,r),l=`${dA}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Ig(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=vk(gk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${OA}" }}`,ref:{variable:oA,key:oA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const fF=`${$O}label:`;function pF(e){if(e.startsWith(fF)){let t=e.slice(fF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function mF(e,t,n,r){let{artifacts:i}=n,a=pg(e),o=`${fF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(jg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,cF([r.ref],`{{ ${ZP(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(jg.map(e=>[e,r.drafts[e]]))}}function hF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${$O}${i}.insert.${t}`,s=`${$O}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:rF,anchor:n,relation:r};let c=ik(o),l=ak(s,o,void 0),u=ck(l),d=sk(l,c);return a.variables[l]=ii(l,P),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${eh}`}) $m }}{{ end }}`}}function gF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!tF(e.name)),i=e=>gF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=gg(o,i);if(tF(o.name)){n.push(s);continue}let c=pg(o),l=a===r?[hF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=hF(t,u,c,`after`),f=oF(t,u,c),p=t.segments[o.name],m=dF(t,u,o,Mg(p)),h=sF(f),g=sF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>aF(e.host,e.template,t.artifacts)),{...mF(o,p,t,m),lead:h,trail:g},{...s,when:$P(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},aF(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:cF(lF(n),$P(t.presetIdent,`true`,e.when))}}}function _F(e,t,n,r,i,a,o){let s=`${$O}${t}.resetLayout`,c=`${$O}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:eF},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},vF(e,o)]}}function vF(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),vF(n,t)]}:{...e,children:[...e.children,t]}}function yF(e,t,n,r,i,a){let{node:o}=zy(e,t),s={presetIdent:XO(t),rootKey:Yk(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=gF(o,s);return n.variables[XP(s.presetIdent)]=QP(s.configured),_F(c,s.presetIdent,s.rootKey,n,r,i,a)}function bF(e){let t={variables:{},actions:{},segments:{}},n=bA(`${$O}help`,UA,[pA],t);t.variables[VP]=ii(VP,P),t.actions[VP]=ai(VP,YP.member),t.segments[VP]={template:ti(VP,...HP),when:mA};let r={kind:`segment`,name:VP},i=n;t.variables[KP]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[UP]={do:[vN,...lA]},t.segments[UP]={template:`{{ if ${JP} }}{{ action "${UP}" "✓ save" }}{{ else }}{{ action "${UP}" "✓ done" }}{{ end }}`,when:mA},t.actions[GP]={rewind:!0},t.actions[WP]={do:[GP,...lA]},t.segments[WP]={template:`{{ action "${WP}" "↩ cancel" }}`,when:`{{ and ${ei(pA)} ${qP} }}`};let a=[{kind:`segment`,name:UP},{kind:`segment`,name:WP}],o={...e.presets},s=[];for(let n of Iy(e.presets)){let c=yF(e,n,t,a,r,i);s.push(c),o[n]={...Ry(e.presets,n),root:c}}let c=YO(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function xF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function SF(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function CF(e,t,n){let r=hg(e,new Set(n.map(mg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const wF=/^-?\d+$/;function TF(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function EF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!wF.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function DF(e,t,n){return r=>r?wF.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function OF(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!wF.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function kF(e){return e===`config`?`set-config`:`set-state`}function AF(e,t,n){return t.kind===`int`?EF(`menu page "${e}"`):t.kind===`range`?DF(t.min,t.max,`${n} stepper "${e}"`):TF(t.allowed,`${n} "${e}"`,kF(n))}function jF(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:OF(e,n,t)}))}function MF(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of jF(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,AF(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function NF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};MF(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=MF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const PF=NF({},`config`,VF);function FF(e,t){return PF.register(e,t)}function IF(e){return PF.gateFor(e)}function LF(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Ky(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[xF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[xF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Ky(e.insertSegmentFrom,t).members.map(t=>xF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function RF(e,t){let n=Wk(e).get(t);return n===void 0?null:String(n)}function zF(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?$k(n.persist):null;e?.scope===`preset-root`&&t.add(Yk(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function BF(e){let t=nF(e);return[...zF(e),...Object.values(e.actions).flatMap(e=>LF(e,t))]}function VF(e){return jF(BF(e),`config`)}function HF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:GF(t.segments,UF(t.segments,e.segments??{})),root:My(e.root??Ty,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:GF(t.presets,WF(t.presets,e.presets??{})),themeDefaults:GF(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function UF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function WF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function GF(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function KF(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Cg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):YF(e,`${t}.cache`,n.cache)}function qF(e){return{required:!0,json:XF(),parse:(t,n,r,i)=>KF(t,n,i,e)??void 0}}const JF={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&QF(n)?{ttl:n}:a_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return a_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=__(`cache.watch_file`,n);return r===null?{watch_file:n}:a_(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:a_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:a_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:a_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function YF(e,t,n){return o_(e,JF,t,n)}function XF(){return w_(JF)}const ZF=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function QF(e){return ZF.test(e)}function $F(e,t,n){if(n===void 0)return{};if(!Qg(n))return e.issues.push({path:t,message:`${t} must be an object, got ${$g(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=s_(e,TI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function eI(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${$g(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function tI(){return{required:!0,json:{enum:[...Tg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Tg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Tg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function nI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Jg(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const rI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:a_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?iI(e,t,n):a_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:a_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function iI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return a_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:a_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function aI(){return{required:!1,json:w_(rI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:o_(e,rI,`${t}.parse`,r.parse)??void 0)}}function oI(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Qg(r.parse)&&`json`in r.parse?sI(e,t,r.default):Yg(e,t,r,`default`)}}function sI(e,t,n){if(n!==void 0)return cI(n)?n:a_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function cI(e){return e!==null&&lI(e)}function lI(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(lI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(lI)}default:return!1}}const uI={value:eI(),default:d_()},dI={path:g_(),type:y_([`string`,`number`,`boolean`]),default:nI()},fI={name:g_(),default:d_()},pI={path:v_(),readMode:y_([`whole`,`first-line`]),parse:aI(),cache:qF(`file`),default:oI()},mI={command:g_(),parse:aI(),cache:qF(`shell`),default:oI()};function hI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const gI={template:g_(),default:d_()},_I=hI(`a template variable recomputes whenever a variable it reads changes`),vI={layout:g_(),default:d_()},yI=hI(`a time variable reads the instant its render is drawn at`),bI={field:tI(),default:d_()},xI=hI(`a git variable is refreshed by the daemon's own watch on the repository`),SI={key:g_(),default:d_()},CI=`kind`;function wI(e,t,n={}){return{...c_(CI,e,t),parse:(r,i,a)=>{t_(r,n,i,a);let o=n_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const TI={tag:CI,noun:`source kind`,memberNoun:`variable`,arms:{literal:wI(`literal`,uI),input:wI(`input`,dI),env:wI(`env`,fI),file:wI(`file`,pI),shell:wI(`shell`,mI),template:wI(`template`,gI,_I),time:wI(`time`,vI,yI),git:wI(`git`,bI,xI),state:wI(`state`,SI)}};function EI(){return C_(TI)}function DI(){return{type:`object`,additionalProperties:EI()}}const OI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function kI(e){let t=OI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const AI=/^[A-Za-z_][A-Za-z0-9_]*$/,jI={pattern:AI.source},MI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},NI={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...jI}}}]},default:MI}},PI=[`label`,`domain`,`default`],FI=[`min`,`max`,`step`,`atLeast`];function II(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function LI(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return II(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return II(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?II(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(Qg(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!FI.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:II(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return II(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function RI(e,t,n){if(!Qg(n))return II(e,t,`${t} must be { label, domain, default }, got ${$g(n)}`);for(let r of Object.keys(n))PI.includes(r)||II(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${PI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||II(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=LI(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!zI(n.default)||!Fg(o,n.default)?II(e,`${t}.default`,`default must be ${zg(o)}, got ${q(n.default)}`):o}function zI(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const BI={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${kg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function VI(e){return jg.includes(e)}function HI(){return{required:!1,json:{type:`object`,propertyNames:{...jI,not:{enum:[...jg]}},additionalProperties:NI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qg(i))return II(e,a,`${a} must be an object of name → { label, domain, default }, got ${$g(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!AI.test(t)){II(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(VI(t)){II(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${BI[t]}`);continue}let r=RI(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const UI=ek.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function WI(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${UI})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!tk(i)?i:II(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${ek.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function GI(){return{required:!1,json:{type:`object`,propertyNames:jI,additionalProperties:MI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qg(i))return II(e,a,`a placement's "settings" must be an object of setting name → value, got ${$g(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))zI(n)?o[t]=n:II(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${$g(n)}`);return o}}}function KI(e){return new Set(Object.keys(e.segments).filter(e=>!tk(e)))}function qI(e,t,n){if(t===void 0)return{};if(!Qg(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${$g(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=e_(e,n.has(i)?$I:QI,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function JI(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?a_(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${kI(t.slice(9))}`)??void 0:qg(e,t,r,n)??void 0}}function YI(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function XI(){return{required:!1,json:DI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return $F(e,`${t}.${n}`,i)}}}const ZI={template:JI(),description:d_(),group:y_(tA),width:YI(),justify:y_(Bg),truncate:y_(Vg),bg:d_(),fg:d_(),when:d_(),palette:h_(),vars:XI(),settings:HI(),missingData:y_(Eg)},QI={noun:`segment key`,fields:ZI},$I={noun:`segment key`,fields:{...ZI,template:d_()}},eL=`#/definitions/LayoutNode`,tL={kind:`container`,direction:`vertical`,children:[]};function nL(e){return{required:!0,json:{const:e},parse:()=>e}}function rL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function iL(){return{required:!0,json:{enum:[...dg]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&dg.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${dg.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function aL(e){return{required:!0,json:{type:`array`,items:{$ref:eL}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${$g(a)}`,line:K(t.source,[`root`])}),[])}}}const oL={noun:`layout-node key`,fields:{kind:nL(`segment`),name:rL(),when:d_(),id:WI(),settings:GI()}},sL=()=>y_(Am),cL={noun:`layout-node key`,fields:{kind:nL(`container`),direction:iL(),children:aL(l_(()=>pL)),when:d_(),distribution:sL()}};function lL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const uL={noun:`layout-node key`,fields:{seg:lL(),when:d_(),id:WI(),settings:GI()}},dL={noun:`layout-node key`,fields:{h:aL(l_(()=>pL)),when:d_(),distribution:sL()}},fL={noun:`layout-node key`,fields:{v:aL(l_(()=>pL)),when:d_(),distribution:sL()}},pL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),tL):{kind:`segment`,name:n};if(!Qg(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${$g(n)}`,line:K(e.source,[`root`])}),tL;if(n.kind===`container`)return e_(e,cL,t,n)??tL;if(n.kind===`segment`)return e_(e,oL,t,n)??tL;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
181
|
+
`,QA=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,$A={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function ej(e){let t=e[$A.socket]??``,n=e[$A.pane]??``;if(t===``||n===``)return null;let r=e[$A.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const tj=[`moves`,`can-move`,`still`];function nj(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const rj=[`carried`,`missing`,`unanswered`];function ij(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:nj(e)===`no`?`unanswered`:`missing`}function aj(e){return{path:e.transcript_path,answered:nj(e)===`yes`}}const oj=[...tj,`failed`,`drawing`],sj=[`statusline`,`frames`],cj=e=>e?.kind===`frames`?`frames`:`statusline`;var lj=class{seen=new Map;see(e,t,n,r){let i=cj(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const uj={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},dj=e=>uj[e];function fj(e){return dj(e).glyphs.kind===`bundled`}function pj(e){return dj(e).glyphs.kind===`configured`}const mj=e=>dj(e).label,hj=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function gj(e,t){let n=t.codePointAt(0);return hj.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&yj(e,t)===!0)}const _j=Object.keys(uj);function vj(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function yj(e,t){let n=vj(e),r=vj(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function bj(e){for(let t of _j){let n=dj(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function xj(e){let t=_j.find(t=>dj(t).term===e);return t===void 0?null:{name:t,version:null}}function Sj(e){let t=bj(e.termtype)??xj(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function Cj(e){let t=e.TERM_PROGRAM,n=_j.find(e=>dj(e).program===t),r=n===void 0?xj(e.TERM):{name:n,version:dj(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function wj(e){switch(e.kind){case`known`:return mj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function Tj(e){switch(e.kind){case`known`:return mj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Ej({name:e,version:t}){let n=dj(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=yj(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Dj=_j.filter(e=>dj(e).links!==null).map(mj).join(`, `);function Oj(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!Na(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!Na(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function kj(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const Aj=[`managed`,`project`],jj=e=>!Aj.includes(e.scope),Mj={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:Aa(t.projectDir)}),user:e=>({scope:`user`,path:e})},Nj=[`drawn`,`boxes`],Pj=1024*1024,Fj=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function Ij(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function Lj(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const Rj=$A.truecolor;function zj(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const Bj={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>zj(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=kj(t.sources,Rj);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${Rj} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,Rj],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Mj[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${Rj} to "1" there`}:o(s)})},Vj={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>zj(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},Hj={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${Fj(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's red strip names), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${Fj(e.value.of)} measured`}},Uj={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},Wj={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
|
|
182
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Lj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${Uj[e]}`)])}}},Gj="re-run `cc-candybar install`";function Kj(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${Gj}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Gj}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Gj}`)}const qj={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${Gj}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Gj}`};case`lost`:return Lj([...Kj(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function Jj({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function Yj(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${M_.join(`|`)}>\``:e.checkout===null?Gj:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Xj(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${Yj(e,`native`)}`];let{bundle:i,source:a}=Jj(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${Yj(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${Yj(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const Zj=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},Qj={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${Zj(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:Lj([...new Set(i.flatMap(e=>Xj(n,r,e)))])}};function $j({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function eM(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const tM={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?eM(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return Lj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=$j(e.value,n),u=Lj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${Nn(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Rn(o.charge.bytes,s)?[`the daemon holds ${Hn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},nM=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function rM(e,t){let n=wj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Ej(e.terminal):{kind:`unknown`}}function iM({identified:e,tmuxClient:t},n){let r=Tj(e),i=rM(e,n),a=wj(e)===null?nM:`${nM}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${Dj}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const aM={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return Lj(iM(t,n))}}},oM=e=>e.filter(e=>e.role===`statusline`),sM={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>uM(e,cM(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:lM(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:Zj(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},cM=e=>{let t=oM(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},lM=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function uM(e,t){let n=Oj(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return lM(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return jj(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const dM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function fM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return Tj(e);case`bundling`:case`unread`:case`configured`:return[mj(e.name),e.version].filter(e=>e!==null).join(` `)}}function pM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return wj(e);case`bundling`:case`unread`:return mj(e.name);case`configured`:{let t=mj(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function mM(e){let t=pM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${dM(e.glyphs)}`}}const hM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=mM(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=fM(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${dM(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=uj[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:yj(i.version,e);if(t===!0)return{ok:!0};let n=mj(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${dM(n)} — set a Nerd Font as its font`)}}}};function gM(e){return e.join(`, `)}function _M(e){return`or set missingData: "ignore" on ${gM(e)}`}function vM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${gM(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${gM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${_M(t)}`]:[`${gM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${_M(t)}`]}function yM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${gM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${gM(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${gM(n)}: ${Zj(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${gM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${gM(n)}`]:[]}function bM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${gM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${_M(t)}`];case`failed`:return[`${gM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const xM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>Lj([...vM(e.pullRequests),...yM(e.rateLimits,t),...bM(e.memento)])};function SM({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${Pj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const CM=[Wj,Qj,tM,qj,aM,Bj,Vj,Hj,sM,hM,xM,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${Zj(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:Lj(e.value.flatMap(SM))}],wM=CM.filter(e=>e.takesMark);function TM(e){return CM.map(t=>({check:t,verdict:t.probe(e)}))}function EM(e){return CM.find(t=>t.name===e)}const DM=/^[^\s"=\\]+$/,OM=e=>DM.test(e)?e:JSON.stringify(e),kM=`${X}doctor.`;function AM(e){let t=`${kM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function jM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?wj(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function MM(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function NM(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=Jj(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const PM=e=>`${e>=0?`+`:``}${Nn(e)}`;function FM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${eM(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${$j(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Un(i.charge)}${i.charge.kind===`stand-in`?`(${PM(-i.charge.gap)})`:``}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function IM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function LM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>RM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${OM(i)}`;let a=oM(r.flatMap(e=>e.bars));return`frames=${oj.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${OM(i)}`}function RM(e){let t=Oj(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function zM(e){let t=kj(e,Rj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${OM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function BM(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function VM(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=mM(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function HM(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function UM(e){return e.flatMap(({check:e,verdict:t})=>{let n=AM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:fg},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:HM(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?fg:dg},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const WM={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function GM(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(WM).map(([t,n])=>[`${e}${t}`,n]))}}const KM=`armed`,qM=`disarmed`,JM=`.armed`,YM=e=>e.endsWith(JM);function XM(e,t,n){let r=`${e}${JM}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${KM}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:KM},[a]:{set:r,to:qM},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:qM}},disarm:a}}const ZM=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function QM(e){return typeof e==`string`&&ZM.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function $M(e){let t=QM(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const eN=[`/compact`,`/model`],tN=`/clear`;function nN(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=XM(`${e}clear`,{arm:tN,confirm:`${tN} ✓ confirm`},[n]);return{template:eN.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${$O} }}`,actions:{...Object.fromEntries(eN.map(e=>[t(e),{slash:$M(e)}])),...r.actions,[n]:{slash:$M(tN)}},variables:r.variables,disarm:r.disarm}}const rN=Array.from({length:10},(e,t)=>(t+1)*1e5),iN=rN[0],aN=rN[rN.length-1];function oN(e){let t;try{t=Da(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=iN&&n<=aN?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${iN}–${aN} tokens)`)}function sN(e,t){let n=Math.min(t??aN,aN),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:rN.filter(e=>e<r).at(-1)??0,higher:rN.find(e=>e>r&&e<=n)??0}}function cN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${$O} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:$M(`/autocompact auto`)},...Object.fromEntries(rN.map(t=>[`${e}${t}`,{slash:$M(`/autocompact ${t}`)}]))}}}const lN=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,uN=`${X}menu`,dN=`open`,fN=`${X}edit`,pN=`${X}toolbar`,mN=GM(X),hN=`${X}commands`,gN=nN(`${hN}.`),_N=`${X}autocompact`,vN=cN(`${_N}.`,lN),yN=e=>({kind:`segment`,name:e}),bN=`${X}tab`,xN=e=>`${bN}.${e}`,SN=e=>`${xN(e)}.toggle`,CN=e=>({variable:bN,key:bN,member:e}),wN=`${X}save`,TN=`${X}preset.save`,EN=`${X}preset.delete`,DN=e=>`${X}${e}`,ON=e=>`${X}apply.${e}`,kN=e=>`${X}reset.${e}`,AN=`${X}themeDefault.save`,jN=`${X}themeDefault.differs`,MN=`${X}themeDefault.theme`,NN={when:`{{ .${jN} }}`,template:`{{ action "${AN}" (printf "⤓ default for %s" .${MN}) }} {{ swatch "${ON(`theme`)}" .${MN} }}`},PN=`${X}resetAll`,FN=`${uN}.toggle`,IN={variable:uN,key:uN,member:dN},LN=`${X}undo`,RN=`${X}back`,zN=`${RN}.step`,BN=`${X}navigation.back`,VN=RN,HN={template:`{{ if gt .${BN} 0 }}{{ action "${RN}" "◁" }}{{ else }}{{ fg (${QA}) "◁" }}{{ end }}`},UN=`${X}redo`,WN=`${X}doctor`,GN=`${WN}.run`,KN=e=>`${WN}.fix.${e}`,qN=(e,t)=>`${WN}.mark.${e}.${t}`,JN=e=>`${WN}.${e}`,YN={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},XN=fk(`${X}pickers`),ZN=e=>`${X}${e}`,QN=e=>`${ZN(e)}.toggle`,$N=e=>VA(e)?fk(`${X}${e}Pickers`):XN,eP=e=>{let t=$N(BA[RA[e].beside]);return{variable:t,key:t,member:e}},tP={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${EN}" (printf "🚮 delete %s" .${pv.preset.effectiveVar}) }}`}},nP=(e,t)=>`${X}list.${e}.${t}`,rP=e=>`${X}resettable.${e}`,iP=e=>e.length===0?`false`:`(or ${e.map(e=>`.${rP(e)}`).join(` `)})`,aP=M_.map(e=>[j_[e].setting,e]),oP={variables:{},actions:{},segments:{}},sP=Object.fromEntries(aP.map(([e,t])=>[e,EA(`${X}help.${e}`,XA[t],[],oP)])),cP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],lP=e=>{let t=t=>`.${I_(e,t)}`,n=cP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${pv[j_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},uP=`{{ if eq .${P_(`by`)} "feed" }} {{ printf "%2d" (int .${P_(`fps`)}) }} fps{{ end }}`,dP=Object.fromEntries(aP.map(([e,t])=>[e,lP(t)])),fP=Object.keys(pv).map(e=>{let t=pv[e],n=Dk(t.configKey),r=wk({label:t.label,domain:n},t.sessionKey,t.effectiveVar,ON(e),$N(BA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>tP[e])}}),pP=e=>fP.filter(t=>BA[t.name]===e),mP=e=>fP.filter(t=>HA(BA[t.name],e)),hP=e=>t=>`(print ${ri(t)} (ternary ${ri(` •`)} "" ${iP(mP(e).map(e=>e.name))}))`,gP=e=>zA.filter(t=>RA[t].beside===e),_P=e=>pP(e).flatMap(e=>[kP(e),...[sP[e.name]].filter(e=>e!==void 0),...gP(e.name).map(e=>Qr(ZN(e),eP(e),IP(e),`drop`))]);new Set(fP.flatMap(e=>[e.sessionKey,e.configKey]));const vP=XM(PN,{arm:`⟲`,confirm:`⟲ reset all?`},fP.map(e=>kN(e.name))),yP=[`unsaved`,`history.undo`,`history.redo`],bP=e=>`${X}${e}`,xP=bP(`unsaved`),SP=(e,t)=>({body:t,shown:`(gt .${bP(e)} 0)`}),CP=[SP(`unsaved`,`{{ action "${wN}" (printf "💾 save %d" .${xP}) }}`),SP(`history.undo`,`{{ action "${LN}" "↶" }}`),SP(`history.redo`,`{{ action "${UN}" "↷" }}`),{body:vP.template,shown:`(or ${iP(fP.map(e=>e.name))} ${vP.armed})`}],wP={when:`{{ or ${CP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+CP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},TP=[{step:vP,place:`door`},{step:gN,place:`session`}],EP=e=>e.map(e=>e.step.disarm),DP=EP(TP),OP=EP(TP.filter(e=>e.place!==`door`));function kP(e){let t=DN(e.name);return e.control.kind===`inline`?yN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>yN(nP(e.name,n)))},`drop`)}function AP(e){return e===uN}function jP(e){let t=yN(uN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[jP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function MP(e){return NP(e)>0?e:jP(e)}function NP(e){let t=0;for(let n of Cg(e))n.kind===`segment`&&AP(n.name)&&(t+=1);return t}function PP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&AP(e.name)||e.opens!==void 0&&PP(e.opens.body,!0):e.children.some(e=>PP(e,n))}const FP={door:{direction:`horizontal`,content:[yN(VN)],after:[yN(fN),yN(wN)]},session:{direction:`vertical`,content:[yN(pN),{kind:`container`,direction:`horizontal`,children:[yN(hN),yN(_N)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[yN(TN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[yN(WN),...CM.map(e=>yN(JN(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[yN(AN)]},toggles:{direction:`horizontal`,content:[],after:[]}};function IP(e){let{direction:t,content:n,after:r}=FP[e];return{kind:`container`,direction:t,children:[...n,..._P(e),...r]}}function LP(e){return e.kind===`segment`?AP(e.name)?Qr(e.name,IN,zP,`above`):e:VP(e)}function RP(){return{kind:`container`,direction:`vertical`,children:[IP(`door`),{kind:`container`,direction:`horizontal`,children:IA.map(({member:e})=>Qr(xN(e),CN(e),IP(e),`drop`))}]}}const zP=RP();function BP(e){let t=new Map;for(let e of Cg(zP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${uN}.fold.${nk(t)}`;return e.actions[i]={set:t,to:r.default},i})}function VP(e){return{...e,children:e.children.map(e=>LP(e))}}function HP(e){let t={variables:{[uN]:ii(uN,P)},actions:{[FN]:ai(uN,dN),[GN]:{doctor:`run`},[fN]:{do:[...hA]},...mN.actions,...gN.actions,...vN.actions,[wN]:{save:!0},[LN]:{undo:!0},[zN]:{back:!0},[RN]:{do:[zN,...DP]},[UN]:{redo:!0},[TN]:{preset:`save`},[AN]:{themeDefault:`save`},[EN]:{preset:`delete`,name:`{{ .${pv.preset.effectiveVar} }}`}},segments:{[uN]:{template:`{{ $door := ${ni(uN,ri(e),ri(`✖`))} }}{{ if ${ei(IN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+uP},[pN]:{template:mN.template},[hN]:{template:gN.template,when:gN.when},[_N]:{template:vN.template,bg:vN.bg,when:vN.when},[VN]:HN,[wN]:wP,[AN]:NN,[TN]:{template:`{{ action "${TN}" "+ preset" }}`},[WN]:{template:`{{ action "${GN}" "🩺 doctor" }}`},[fN]:{template:`{{ action "${fN}" "✎ arrange" "✎ done" }}`}}};t.variables[jN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[MN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[BN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of yP)t.variables[bP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[bN]=ii(bN,`session`);for(let{member:e,label:n}of IA){t.actions[SN(e)]=ai(bN,e),t.actions[xN(e)]={do:[SN(e),...OP]};let r=hP(e);t.segments[xN(e)]={template:`{{ ${ni(xN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,gN.variables,vP.variables),WP(t),UP(t),t.actions[uN]={do:[FN,...DP,...BP(t)]},t}function UP(e){for(let t of CM){let n=AM(t.name),r=KN(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?Nj:[];for(let n of i)e.actions[qN(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${qN(t.name,e)}" "${YN[e]}" }}`).join(``);e.segments[JN(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${dg}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function WP(e){for(let t of fP){Object.assign(e.actions,t.control.actions);let n=kN(t.name);e.actions[n]={reset:t.configKey},e.variables[rP(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${rP(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[DN(t.name)]={template:`${t.control.template}${dP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[nP(t.name,r)]=n})}Object.assign(e.actions,vP.actions),Object.assign(e.variables,oP.variables),Object.assign(e.actions,oP.actions),Object.assign(e.segments,oP.segments);for(let t of zA){let n=eP(t);e.actions[QN(t)]=ai(n.key,n.member),e.segments[ZN(t)]={template:`{{ action "${QN(t)}" ${hP(t)(RA[t].trigger)} }}`}}}function GP(e){let{variables:t,actions:n}=wA();Object.assign(e.variables,t),Object.assign(e.actions,n)}function KP(e){let t=HP(e.globals.menuGlyph??`🍫`);GP(t);let n={...e.presets},r=[];for(let t of Hy(e.presets)){let{node:i}=Gy(e,t),a=LP(MP(i));r.push(a),n[t]={...Wy(e.presets,t),root:a}}let i=tk(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const qP=`${ak}live`,JP=[`☐ live`,`☑ live`],YP=`${ak}done`,XP=`${ak}cancel`,ZP=`${ak}rewind`,QP=`${ak}changes`,$P=`(gt .${QP} 0)`,eF=`(or ${$P} (gt .${xP} 0))`,tF={variable:qP,key:qP,member:`open`};function nF(e){return`${ak}configuring.p${e}`}function rF(e){return`and ${ei(yA)} (not ${ei(tF)}) (ne .${nF(e)} "true")`}function iF(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${fA} "${Zr(e)}")`).join(` `)} false }}`}}function aF(e,t,n){return`{{ if ${rF(e)} }}${t}{{ else }}${n}{{ end }}`}const oF=`{{ and ${ei(yA)} .preset.customized }}`,sF=sk;function cF(e){return new Map([...Xy(e),...uF(e)])}const lF=`${ak}addable`;function uF(e){return new Map([[lF,{members:Object.keys(e.segments).filter(e=>!sF(e)),library:{groups:cA.map(e=>({id:e,label:lA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function dF(e,t,n){return n.segments[e]={template:t,when:bA,bg:OA},{kind:`segment`,name:e}}function fF(e,t,n){let r=`${ak}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${eh}`}) (action "${r}" "✖") }}`}function pF(e){return`{{ if ${ei(yA)} }}${e}{{ end }}`}function mF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(yA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function hF(e){return e.flatMap(e=>[...Cg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function gF(e,t,n){return`${_A}${e}.${t}.${n}`}function _F(e,t,n,r){let i=yg(n),a=`${ak}${e.presetIdent}`,o=vA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=fk(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:fA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=gF(e.presetIdent,i,r),l=`${_A}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Hg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=wk(Sk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${PA}" }}`,ref:{variable:fA,key:fA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const vF=`${ak}label:`;function yF(e){if(e.startsWith(vF)){let t=e.slice(vF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function bF(e,t,n,r){let{artifacts:i}=n,a=yg(e),o=`${vF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Lg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,mF([r.ref],`{{ ${rF(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Lg.map(e=>[e,r.drafts[e]]))}}function xF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${ak}${i}.insert.${t}`,s=`${ak}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:lF,anchor:n,relation:r};let c=uk(o),l=dk(s,o,void 0),u=mk(l),d=pk(l,c);return a.variables[l]=ii(l,P),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${eh}`}) $m }}{{ end }}`}}function SF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!sF(e.name)),i=e=>SF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Sg(o,i);if(sF(o.name)){n.push(s);continue}let c=yg(o),l=a===r?[xF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=xF(t,u,c,`after`),f=fF(t,u,c),p=t.segments[o.name],m=_F(t,u,o,Rg(p)),h=pF(f),g=pF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>dF(e.host,e.template,t.artifacts)),{...bF(o,p,t,m),lead:h,trail:g},{...s,when:aF(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},dF(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:mF(hF(n),aF(t.presetIdent,`true`,e.when))}}}function CF(e,t,n,r,i,a,o){let s=`${ak}${t}.resetLayout`,c=`${ak}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:oF},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},wF(e,o)]}}function wF(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),wF(n,t)]}:{...e,children:[...e.children,t]}}function TF(e,t,n,r,i,a){let{node:o}=Gy(e,t),s={presetIdent:nk(t),rootKey:tA(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=SF(o,s);return n.variables[nF(s.presetIdent)]=iF(s.configured),CF(c,s.presetIdent,s.rootKey,n,r,i,a)}function EF(e){let t={variables:{},actions:{},segments:{}},n=EA(`${ak}help`,YA,[yA],t);t.variables[qP]=ii(qP,P),t.actions[qP]=ai(qP,tF.member),t.segments[qP]={template:ti(qP,...JP),when:bA};let r={kind:`segment`,name:qP},i=n;t.variables[QP]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[YP]={do:[wN,...hA]},t.segments[YP]={template:`{{ if ${eF} }}{{ action "${YP}" "✓ save" }}{{ else }}{{ action "${YP}" "✓ done" }}{{ end }}`,when:bA},t.actions[ZP]={rewind:!0},t.actions[XP]={do:[ZP,...hA]},t.segments[XP]={template:`{{ action "${XP}" "↩ cancel" }}`,when:`{{ and ${ei(yA)} ${$P} }}`};let a=[{kind:`segment`,name:YP},{kind:`segment`,name:XP}],o={...e.presets},s=[];for(let n of Hy(e.presets)){let c=TF(e,n,t,a,r,i);s.push(c),o[n]={...Wy(e.presets,n),root:c}}let c=tk(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function DF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function OF(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function kF(e,t,n){let r=xg(e,new Set(n.map(bg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const AF=/^-?\d+$/;function jF(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function MF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!AF.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function NF(e,t,n){return r=>r?AF.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function PF(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!AF.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function FF(e){return e===`config`?`set-config`:`set-state`}function IF(e,t,n){return t.kind===`int`?MF(`menu page "${e}"`):t.kind===`range`?NF(t.min,t.max,`${n} stepper "${e}"`):jF(t.allowed,`${n} "${e}"`,FF(n))}function LF(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:PF(e,n,t)}))}function RF(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of LF(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,IF(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function zF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};RF(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=RF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const BF=zF({},`config`,qF);function VF(e,t){return BF.register(e,t)}function HF(e){return BF.gateFor(e)}function UF(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Qy(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[DF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[DF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Qy(e.insertSegmentFrom,t).members.map(t=>DF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function WF(e,t){let n=Xk(e).get(t);return n===void 0?null:String(n)}function GF(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?aA(n.persist):null;e?.scope===`preset-root`&&t.add(tA(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function KF(e){let t=cF(e);return[...GF(e),...Object.values(e.actions).flatMap(e=>UF(e,t))]}function qF(e){return LF(KF(e),`config`)}function JF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:ZF(t.segments,YF(t.segments,e.segments??{})),root:Ry(e.root??jy,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:ZF(t.presets,XF(t.presets,e.presets??{})),themeDefaults:ZF(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function YF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function XF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function ZF(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function QF(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${kg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):tI(e,`${t}.cache`,n.cache)}function $F(e){return{required:!0,json:nI(),parse:(t,n,r,i)=>QF(t,n,i,e)??void 0}}const eI={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&iI(n)?{ttl:n}:d_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return d_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=C_(`cache.watch_file`,n);return r===null?{watch_file:n}:d_(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:d_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:d_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:d_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function tI(e,t,n){return f_(e,eI,t,n)}function nI(){return A_(eI)}const rI=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function iI(e){return rI.test(e)}function aI(e,t,n){if(n===void 0)return{};if(!i_(n))return e.issues.push({path:t,message:`${t} must be an object, got ${a_(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=p_(e,jI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function oI(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${a_(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function sI(){return{required:!0,json:{enum:[...jg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!jg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${jg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function cI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return e_(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const lI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:d_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?uI(e,t,n):d_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:d_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function uI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return d_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:d_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function dI(){return{required:!1,json:A_(lI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:f_(e,lI,`${t}.parse`,r.parse)??void 0)}}function fI(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>i_(r.parse)&&`json`in r.parse?pI(e,t,r.default):t_(e,t,r,`default`)}}function pI(e,t,n){if(n!==void 0)return mI(n)?n:d_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function mI(e){return e!==null&&hI(e)}function hI(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(hI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(hI)}default:return!1}}const gI={value:oI(),default:__()},_I={path:S_(),type:T_([`string`,`number`,`boolean`]),default:cI()},vI={name:S_(),default:__()},yI={path:w_(),readMode:T_([`whole`,`first-line`]),parse:dI(),cache:$F(`file`),default:fI()},bI={command:S_(),parse:dI(),cache:$F(`shell`),default:fI()};function xI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const SI={template:S_(),default:__()},CI=xI(`a template variable recomputes whenever a variable it reads changes`),wI={layout:S_(),default:__()},TI=xI(`a time variable reads the instant its render is drawn at`),EI={field:sI(),default:__()},DI=xI(`a git variable is refreshed by the daemon's own watch on the repository`),OI={key:S_(),default:__()},kI=`kind`;function AI(e,t,n={}){return{...m_(kI,e,t),parse:(r,i,a)=>{s_(r,n,i,a);let o=c_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const jI={tag:kI,noun:`source kind`,memberNoun:`variable`,arms:{literal:AI(`literal`,gI),input:AI(`input`,_I),env:AI(`env`,vI),file:AI(`file`,yI),shell:AI(`shell`,bI),template:AI(`template`,SI,CI),time:AI(`time`,wI,TI),git:AI(`git`,EI,DI),state:AI(`state`,OI)}};function MI(){return k_(jI)}function NI(){return{type:`object`,additionalProperties:MI()}}const PI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function FI(e){let t=PI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const II=/^[A-Za-z_][A-Za-z0-9_]*$/,LI={pattern:II.source},RI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},zI={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...LI}}}]},default:RI}},BI=[`label`,`domain`,`default`],VI=[`min`,`max`,`step`,`atLeast`];function HI(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function UI(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return HI(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return HI(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?HI(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(i_(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!VI.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:HI(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return HI(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function WI(e,t,n){if(!i_(n))return HI(e,t,`${t} must be { label, domain, default }, got ${a_(n)}`);for(let r of Object.keys(n))BI.includes(r)||HI(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${BI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||HI(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=UI(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!GI(n.default)||!Vg(o,n.default)?HI(e,`${t}.default`,`default must be ${Gg(o)}, got ${q(n.default)}`):o}function GI(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const KI={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Fg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function qI(e){return Lg.includes(e)}function JI(){return{required:!1,json:{type:`object`,propertyNames:{...LI,not:{enum:[...Lg]}},additionalProperties:zI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return HI(e,a,`${a} must be an object of name → { label, domain, default }, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!II.test(t)){HI(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(qI(t)){HI(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${KI[t]}`);continue}let r=WI(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const YI=ok.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function XI(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${YI})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!sk(i)?i:HI(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${ok.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function ZI(){return{required:!1,json:{type:`object`,propertyNames:LI,additionalProperties:RI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return HI(e,a,`a placement's "settings" must be an object of setting name → value, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))GI(n)?o[t]=n:HI(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${a_(n)}`);return o}}}function QI(e){return new Set(Object.keys(e.segments).filter(e=>!sk(e)))}function $I(e,t,n){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${a_(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=o_(e,n.has(i)?aL:iL,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function eL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?d_(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${FI(t.slice(9))}`)??void 0:$g(e,t,r,n)??void 0}}function tL(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function nL(){return{required:!1,json:NI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return aI(e,`${t}.${n}`,i)}}}const rL={template:eL(),description:__(),group:T_(sA),width:tL(),justify:T_(Kg),truncate:T_(qg),bg:__(),fg:__(),when:__(),palette:x_(),vars:nL(),settings:JI(),missingData:T_(Mg)},iL={noun:`segment key`,fields:rL},aL={noun:`segment key`,fields:{...rL,template:__()}},oL=`#/definitions/LayoutNode`,sL={kind:`container`,direction:`vertical`,children:[]};function cL(e){return{required:!0,json:{const:e},parse:()=>e}}function lL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function uL(){return{required:!0,json:{enum:[..._g]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&_g.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${_g.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function dL(e){return{required:!0,json:{type:`array`,items:{$ref:oL}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${a_(a)}`,line:K(t.source,[`root`])}),[])}}}const fL={noun:`layout-node key`,fields:{kind:cL(`segment`),name:lL(),when:__(),id:XI(),settings:ZI()}},pL=()=>T_(jm),mL={noun:`layout-node key`,fields:{kind:cL(`container`),direction:uL(),children:dL(h_(()=>yL)),when:__(),distribution:pL()}};function hL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const gL={noun:`layout-node key`,fields:{seg:hL(),when:__(),id:XI(),settings:ZI()}},_L={noun:`layout-node key`,fields:{h:dL(h_(()=>yL)),when:__(),distribution:pL()}},vL={noun:`layout-node key`,fields:{v:dL(h_(()=>yL)),when:__(),distribution:pL()}},yL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),sL):{kind:`segment`,name:n};if(!i_(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${a_(n)}`,line:K(e.source,[`root`])}),sL;if(n.kind===`container`)return o_(e,mL,t,n)??sL;if(n.kind===`segment`)return o_(e,fL,t,n)??sL;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
183
183
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
184
|
-
New: { h: ["seg1", "seg2"] }`,line:K(e.source,[`root`])}),tL;if(n.kind===`group`){let r=e_(e,bL,t,n);return r===null?tL:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),SL(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:K(e.source,[`root`])}),tL}if(a){let r=e_(e,uL,t,n);return r===null?tL:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=e_(e,dL,t,n);return r===null?tL:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=e_(e,fL,t,n);return r===null?tL:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:K(e.source,[`root`])}),tL};function mL(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Cy.source},additionalProperties:{$ref:eL}},parse:(e,t,n,r)=>{let i=r[n];if(!Qg(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${$g(i)}`,line:K(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Cy.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:K(e.source,[...t.split(`.`),n,r])});continue}a[r]=pL(e,`${t}.${n}.${r}`,o)}return a}}}const hL={noun:`root key`,fields:{rows:mL(),when:d_(),distribution:sL()}};function gL(e,t,n){return Qg(n)&&`rows`in n?e_(e,hL,t,n)??{rows:{}}:pL(e,t,n)}function _L(){return{required:!0,json:{type:`string`,pattern:Cy.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Cy.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${P}", got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}function vL(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}}function yL(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=qg(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:K(e.source,[...t.split(`.`),n])});return}return i}}}}const bL={noun:`layout-node key`,fields:{kind:nL(`group`),name:_L(),label:yL(),open:f_(),direction:y_(dg),key:vL(),bg:d_(),fg:d_(),when:d_(),distribution:sL(),children:aL(l_(()=>pL))}};function xL(e){return e.key??`groups.`+e.name}function SL(e){let t=ZO+e.name;return Qr(t,{variable:t,key:xL(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function CL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function wL(e,t){rk(e,t,ZO,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&CL(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&xL(t)===xL(r)&&CL(e,t.path,`group "${t.name}" shares key "${xL(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=xL(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&CL(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=ZO+e.name,r=xL(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ii(r,i.get(r)),o[t]=ai(r,e.name),s[t]={template:ti(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const TL=`menu`,EL=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,DL=e=>e.kind===`call`&&e.name===`dict`,OL=e=>e.kind===`literal`&&typeof e.value!=`object`,kL=e=>Yr(``,e,2)===void 0;function AL(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&DL(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(DL))return t(`whose options (dict …) is not its last argument — ${EL}`);if(i!==void 0&&a===void 0&&!OL(i)&&kL(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Yr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${EL}`);let c=a===void 0?{}:fw(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=fk(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=nk(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${ok(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function jL(e){let t=xS({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===TL).map(AL)}catch{return`parse-failed`}}function ML(e){let t=xS({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(TL)}catch{return!1}}function NL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function PL(e,t){rk(e,t,QO,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))ML(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:K(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&ML(i)&&NL(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of _g(Ay(t.root)))typeof n.when==`string`&&ML(n.when)&&NL(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!ML(r))continue;let n=jL(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:FL(r.apply);n!==void 0&&NL(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function FL(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(ik(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function IL(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Iy(e.presets)){let a=new Map,s=new Map;for(let c of _g(zy(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,jL(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=pg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||FL(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=ik(i),f=ak(u,i,l.key),p=ck(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=sk(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=ai(f,d),n[f]=ii(f,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const LL=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function RL(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function zL(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function BL(e,t){if(t===void 0)return{};if(!Qg(t))return Z(e,`actions`,`actions must be an object, got ${$g(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=VL(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function VL(e,t,n){if(!Qg(n))return Z(e,t,`${t} must be an action object, got ${$g(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=LL.filter(e=>e in n);return r.length===1?HL[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${LL.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const HL={set:(e,t,n)=>SR(e,t,n,`set`,vR),persist:(e,t,n)=>SR(e,t,n,`persist`,yR),copy:UL(`copy`),open:UL(`open`),reset:WL,undo:KL(`undo`),redo:KL(`redo`),back:KL(`back`),rewind:KL(`rewind`),save:KL(`save`),preset:qL,themeDefault:JL,doctor:XL,ceiling:ZL,slash:QL,do:$L};function UL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=qg(t,n,r,e);return i===null?null:{[e]:i}}}function WL(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=eR(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const GL={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function KL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${GL[e]}), got ${q(r[e])}`),null)}}function qL(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${q(r)}`),null;if(r===`save`)return{preset:`save`};let a=qg(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function JL(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${q(n.themeDefault)}`),null)}const YL={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function XL(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(YL,r),a=i?YL[r]:[...new Set(Object.values(YL).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(YL).map(e=>`"${e}"`).join(`, `)}, got ${q(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?vM:_M;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${q(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return Dj.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${Dj.map(e=>`"${e}"`).join(` or `)}, got ${q(c)}`),null)}function ZL(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Z(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${q(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Z(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${q(a)}`),null):{ceiling:`set`,to:a}}function QL(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=KM(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}function $L(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${q(r)}`),null):{do:r}}function eR(e,t,n,r,i,a){let o=qg(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const tR={set:`the SessionState key to write`,persist:`the config globals field to write`};function nR(e,t,n,r){let i=tR[r],a=eR(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function rR(e){return e===`set`?`set-state`:`set-config`}const iR={to:CR(`set`)},aR={to:CR(`persist`)},oR={from:wR(`set`)},sR={from:wR(`persist`)},cR={min:kR(),max:kR(),by:kR()},lR={int:ER()},uR={cycle:TR(`set`)},dR={cycle:TR(`persist`)},fR={removeSegment:DR(`removeSegment`)},pR={insertSegment:DR(`insertSegment`),anchor:DR(`anchor`),relation:OR()},mR={insertSegmentFrom:wR(`persist`),anchor:DR(`anchor`),relation:OR()},hR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},gR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function _R(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>n_(e,t,n,r),c=b_(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?u_(s,...n):s}}const vR=[_R(`set`,iR),_R(`set`,oR),_R(`set`,cR,[hR,gR]),_R(`set`,lR),_R(`set`,uR)],yR=[_R(`persist`,aR),_R(`persist`,sR),_R(`persist`,cR,[hR,gR]),_R(`persist`,dR),_R(`persist`,fR),_R(`persist`,pR,[],[`insertSegment`]),_R(`persist`,mR,[],[`insertSegmentFrom`])];function bR(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function xR(e){let t=bR(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function SR(e,t,n,r,i){let a=nR(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${xR(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function CR(e){let t=rR(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>eR(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function wR(e){let t=rR(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${q(o)}`)}}}function TR(e){let t=rR(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${$g(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function ER(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${q(r[n])}`);return}return!0}}}function DR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=qg(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function OR(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${q(i)}`);return}return i}}}function kR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${q(i)}`);return}return i}}}function AR(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const jR={noun:`style key`,fields:{hueShift:m_(),chromaScale:m_({min:0}),lightnessScale:m_(),lightnessShift:m_()}};function MR(e,t){if(!Qg(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${$g(t)}`,line:K(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:K(e.source,[`styles`,r])});continue}if(eg(r)){e.issues.push({path:`styles.${r}`,message:AR(`styles.${r}`,r,`globals.endcaps`),line:K(e.source,[`styles`,r])});continue}let t=e_(e,jR,`styles.${r}`,i);t!==null&&(n[r]={...Sc,...t})}return n}const NR={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:gL(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Lk(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Ik(e,`${t}.${n}`,r[n])}}};function PR(e,t){if(!Qg(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${$g(t)}`,line:K(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:K(e.source,[`presets`,r])});continue}let t=e_(e,NR,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function FR(e,t){if(t===void 0)return{};if(!Qg(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${$g(t)}`,line:K(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${q(i)}`,line:K(e.source,[`helpers`,r])});continue}n[r]=i}return n}const IR=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function LR(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function RR(e){let t=IR.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${LR(t)}`}function zR(e){let t=IR.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${LR(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function BR(e,t){let n=new Map;for(let e of Object.keys(t)){let t=XO(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:K(e.source,[`presets`])})}function VR(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Lh(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:eg(i)?AR(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:K(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:K(e.source,[`globals`,`preset`])}),BR(e,t.presets);let i=hb(t);for(let t of i.names)t!==`settings`&&!t.startsWith(WR)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:K(e.source,[`variables`,t])});let a=(t,n,r)=>{DP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iN}" ${DP(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),OP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iN}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of _g(t)){if(e.kind!==`segment`)continue;let t=pg(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=hg(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||fg[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of jy(n,r)){let n=K(e.source,o.split(`.`));if(a.when!==void 0&&(nz(e,`${o}.when`,a.when,i,{line:n}),tz(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(wP(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${iN}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${iN}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${kI(a.name)}`,line:n}),QR(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,ky(t.root)]]);for(let e of Iy(t.presets)){let{node:n,path:r}=zy(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,K(e.source,t.split(`.`)));lz(e,t,i,()=>!0)}const HR=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function UR(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=K(e.source,[`actions`,n,r]);if(!Iy(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Iy(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${kI(i)}`,line:c})},p=new Set(mg(zy(t,a).node)),m=(r,i)=>{!OI.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${kI(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const WR=`settings.`;function GR(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>WR+e)])}}function KR(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:K(e.source,[`segments`,t,`settings`,n])})},a=YR(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Pg(n,JR(n)))i(e,`the defaults do not stand together: ${t}`)}function qR(e){return YR(e).length>0||Pg(e,JR(e)).length>0}function JR(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function YR(e){let t=t=>Ng(XR(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Ng(XR(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${ZR(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function XR(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function ZR(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Ng(n)!==void 0).map(([e])=>e)}function QR(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Mg(a),s=`${r}: placement "${pg(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Fg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Oh(a):``}, but it must be ${zg(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Fg(o[e],t))||qR(o)))for(let{message:t}of Pg(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function $R(e,t,n,r,i){n.kind===`template`&&nz(e,`${t}.template`,n.template,r,{segCtx:i}),wg(n)&&`key`in n.cache&&nz(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function ez(e,t,n,r,i){if(!(!wg(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:K(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function tz(e,t,n,r){try{iA.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function nz(e,t,n,r,i){for(let[a,o]of sb(n,r.helpers)){if(mb(a,r))continue;if(a.startsWith(WR)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??K(e.source,t.split(`.`))});continue}if(o!==null){rz(e,o,`Template references unknown variable ".${a}"${zR(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&mb(n,r)?` (segment-local vars are namespaced — write ".${n}")`:zR(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??K(e.source,t.split(`.`))})}}function rz(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:K(e.source,[`helpers`,t])})}function iz(e,t,n,r,i){let a=n.set,o=xk(sv[r].configKey),s=`${a} takes ${hk(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:K(e.source,[`actions`,t,`min`])});return}let c=sz(n,i);if(c===oz){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:K(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!mk(o,e.value,i));if(l.length!==0){if(a===sv.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>eg(e.value)))){let r=sv.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:AR(`actions.${t}.to`,n.to,`set: "${r}", to`),line:K(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:K(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=az?r.join(`, `):`${r.slice(0,az).join(`, `)} and ${r.length-az} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:K(e.source,[`actions`,t,n])})}}}const az=3,oz=Symbol(`any integer`);function sz(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?Ky(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:oz}function cz(e,t){return Object.entries(e).filter(([e])=>t(e))}function lz(e,t,n,r){let i=nF(t),a=Gy(i);for(let[n,o]of cz(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${Jy(r,i)}`,line:K(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;dv.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:K(e.source,[`actions`,n,`set`])});let s=hv.get(o.set);s!==void 0&&iz(e,n,o,s,i)}for(let[n,i]of cz(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&zL(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:K(e.source,[`actions`,n,`do`])})});for(let[n,i]of cz(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=$k(r);if(o===null){let t=Vk(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${Hk().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:K(e.source,[`actions`,n,a])});continue}let s=HR.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){UR(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Iy(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Iy(t.presets).join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Oh(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${kI(o.segment)}`,line:K(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:K(e.source,[`actions`,n,a])})}}for(let[i,a]of cz(t.variables,r)){$R(e,`variables.${i}`,a,n);let t=RR(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:K(e.source,[`variables`,i])})}for(let[i,a]of cz(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))$R(e,`segments.${i}.vars.${t}`,r,n,i);let r=Mg(a);KR(e,i,r);let o=GR(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){nz(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of db(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){rz(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:K(e.source,[`segments`,i,n])})}}}}for(let[i,a]of cz(t.variables,r))ez(e,`variables.${i}`,a,n);for(let[i,a]of cz(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))ez(e,`segments.${i}.vars.${t}`,r,n,i)}function uz(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=dz(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:K(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function dz(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of sb(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),wg(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function fz(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function pz(e,t){return s.resolve(e,fz(t))}function mz(e,t){return typeof t==`string`&&t!==``?pz(e,t):void 0}function hz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const gz=new Set([`data`,`segments`,`helpers`,`actions`]),_z=`plugin.json5`,vz=/^[a-z][a-z0-9_]*$/;function yz(e){let t=s.basename(s.dirname(e));return vz.test(t)?t:void 0}const bz=`plugins.`;function xz(e){return`${bz}${e}.data`}function Sz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Cz(e)}}}function Cz(e){return e instanceof Hg?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function wz(e,t){return e.map(e=>pz(s.dirname(t),e))}function Tz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=yz(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${_z}, and the folder's name is the plugin's: move this file to <dir>/<name>/${_z} and list that`;return o(t,a===void 0?e.config:Oz(Dz(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${vz}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=Dz(e.config,a),u=Sz(()=>{let i=p.readFileSync(n,`utf-8`),o=HF(Pz(n,a,{source:i,json:ui.default.parse(i)},t),l);return r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,Oz(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function Ez(e){let t=`${bz}${e}.`;return e=>e.startsWith(t)}function Dz(e,t){let n=Ez(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function Oz(e,t,n){return{...e,variables:{...e.variables,[xz(t)]:{kind:`dropped`,reason:hz(n),definition:n.path}}}}function kz(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Az(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(kz)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:hz(e)}));return t=>{let i=kz(t);if(i===void 0)return[];let a=e.config.variables[xz(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function jz(e,t){let n=Iy(e.presets).flatMap(t=>[..._g(zy(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,Mz(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=kz(t),r=n===void 0?void 0:e.variables[xz(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>db(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...pb(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${xz(kz(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function Mz(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,Nz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function Nz(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function Pz(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Hg(e,a)};if(!Qg(r))return a.push({path:``,message:`a plugin definition must be an object, got ${$g(r)}`}),o();for(let e of Object.keys(r))gz.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...gz].join(`, `)}`});let s=Bz(r.data,e,i,a);if(Qg(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(jh()),groups:[]},l=$F(c,`data`,{[xz(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!Qg(t)||!Qg(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=Qg(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:Iz(t,Rz(t,qI(c,r.segments,new Set))),helpers:Iz(t,FR(c,r.helpers)),actions:Iz(t,zz(t,BL(c,r.actions)))};for(let[e,t]of Fz(u))try{iA.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*Fz(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function Iz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${bz}${e}.${t}`,n]))}function Lz(e,t){return`${bz}${e}.${t}`}function Rz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,n.kind===`state`?{...n,key:Lz(e,n.key)}:n]))}]))}function zz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Lz(e,n.set)}:n]))}function Bz(e,t,n,r){if(typeof e==`string`&&e!==``)return pz(s.dirname(t),e);if(Qg(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(Qg(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function Vz(e){let t=[...[...(process.env.XDG_DATA_DIRS||Wz()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),Hz(),...e===null?[]:[s.join(e,Uz)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function Hz(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const Uz=s.join(`.cc-candybar`,`plugins`);function Wz(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function Gz(e){let t=Vz(e),n=new Map,r=[],i=[];for(let e of t){let t=Kz(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,_z));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${_z}: move this file to ${s.join(e,`<name>`,_z)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function Kz(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||qz(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function qz(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function Jz(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const Yz=[`json5`,`json`];function Xz(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?Yz.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...Yz.map(e=>s.join(r,`.cc-candybar.${e}`)),...Yz.map(e=>`${Zz()}.${e}`)])]}function Zz(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function Qz(e,t,n){let r=[],i=new Map;for(let a of Xz(e,t,n)){let e=Jz(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:$z(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function $z(e){let t=Zz();return e.find(e=>Yz.some(n=>e===`${t}.${n}`))??`${t}.${Yz[0]}`}function eB(e,t,n){let r=Qz(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function tB(e){return nB(e).join(`
|
|
185
|
-
`)||null}function
|
|
184
|
+
New: { h: ["seg1", "seg2"] }`,line:K(e.source,[`root`])}),sL;if(n.kind===`group`){let r=o_(e,EL,t,n);return r===null?sL:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),OL(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:K(e.source,[`root`])}),sL}if(a){let r=o_(e,gL,t,n);return r===null?sL:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=o_(e,_L,t,n);return r===null?sL:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=o_(e,vL,t,n);return r===null?sL:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:K(e.source,[`root`])}),sL};function bL(){return{required:!0,json:{type:`object`,propertyNames:{pattern:ky.source},additionalProperties:{$ref:oL}},parse:(e,t,n,r)=>{let i=r[n];if(!i_(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!ky.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:K(e.source,[...t.split(`.`),n,r])});continue}a[r]=yL(e,`${t}.${n}.${r}`,o)}return a}}}const xL={noun:`root key`,fields:{rows:bL(),when:__(),distribution:pL()}};function SL(e,t,n){return i_(n)&&`rows`in n?o_(e,xL,t,n)??{rows:{}}:yL(e,t,n)}function CL(){return{required:!0,json:{type:`string`,pattern:ky.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!ky.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${P}", got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}function wL(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}}function TL(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=$g(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:K(e.source,[...t.split(`.`),n])});return}return i}}}}const EL={noun:`layout-node key`,fields:{kind:cL(`group`),name:CL(),label:TL(),open:v_(),direction:T_(_g),key:wL(),bg:__(),fg:__(),when:__(),distribution:pL(),children:dL(h_(()=>yL))}};function DL(e){return e.key??`groups.`+e.name}function OL(e){let t=rk+e.name;return Qr(t,{variable:t,key:DL(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function kL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function AL(e,t){lk(e,t,rk,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&kL(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&DL(t)===DL(r)&&kL(e,t.path,`group "${t.name}" shares key "${DL(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=DL(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&kL(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=rk+e.name,r=DL(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ii(r,i.get(r)),o[t]=ai(r,e.name),s[t]={template:ti(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const jL=`menu`,ML=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,NL=e=>e.kind===`call`&&e.name===`dict`,PL=e=>e.kind===`literal`&&typeof e.value!=`object`,FL=e=>Yr(``,e,2)===void 0;function IL(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&NL(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(NL))return t(`whose options (dict …) is not its last argument — ${ML}`);if(i!==void 0&&a===void 0&&!PL(i)&&FL(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Yr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${ML}`);let c=a===void 0?{}:vw(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=vk(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=ck(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${fk(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function LL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===jL).map(IL)}catch{return`parse-failed`}}function RL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(jL)}catch{return!1}}function zL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function BL(e,t){lk(e,t,ik,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))RL(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:K(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&RL(i)&&zL(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of Cg(Iy(t.root)))typeof n.when==`string`&&RL(n.when)&&zL(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!RL(r))continue;let n=LL(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:VL(r.apply);n!==void 0&&zL(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function VL(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(uk(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function HL(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Hy(e.presets)){let a=new Map,s=new Map;for(let c of Cg(Gy(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,LL(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=yg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||VL(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=uk(i),f=dk(u,i,l.key),p=mk(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=pk(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=ai(f,d),n[f]=ii(f,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const UL=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function WL(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function GL(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function KL(e,t){if(t===void 0)return{};if(!i_(t))return Z(e,`actions`,`actions must be an object, got ${a_(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=qL(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function qL(e,t,n){if(!i_(n))return Z(e,t,`${t} must be an action object, got ${a_(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=UL.filter(e=>e in n);return r.length===1?JL[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${UL.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const JL={set:(e,t,n)=>OR(e,t,n,`set`,wR),persist:(e,t,n)=>OR(e,t,n,`persist`,TR),copy:YL(`copy`),open:YL(`open`),reset:XL,undo:QL(`undo`),redo:QL(`redo`),back:QL(`back`),rewind:QL(`rewind`),save:QL(`save`),preset:$L,themeDefault:eR,doctor:nR,ceiling:rR,slash:iR,do:aR};function YL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=$g(t,n,r,e);return i===null?null:{[e]:i}}}function XL(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=oR(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const ZL={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function QL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${ZL[e]}), got ${q(r[e])}`),null)}}function $L(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${q(r)}`),null;if(r===`save`)return{preset:`save`};let a=$g(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function eR(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${q(n.themeDefault)}`),null)}const tR={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function nR(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(tR,r),a=i?tR[r]:[...new Set(Object.values(tR).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(tR).map(e=>`"${e}"`).join(`, `)}, got ${q(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?wM:CM;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${q(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return Nj.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${Nj.map(e=>`"${e}"`).join(` or `)}, got ${q(c)}`),null)}function rR(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Z(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${q(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Z(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${q(a)}`),null):{ceiling:`set`,to:a}}function iR(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=QM(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}function aR(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${q(r)}`),null):{do:r}}function oR(e,t,n,r,i,a){let o=$g(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const sR={set:`the SessionState key to write`,persist:`the config globals field to write`};function cR(e,t,n,r){let i=sR[r],a=oR(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function lR(e){return e===`set`?`set-state`:`set-config`}const uR={to:kR(`set`)},dR={to:kR(`persist`)},fR={from:AR(`set`)},pR={from:AR(`persist`)},mR={min:FR(),max:FR(),by:FR()},hR={int:MR()},gR={cycle:jR(`set`)},_R={cycle:jR(`persist`)},vR={removeSegment:NR(`removeSegment`)},yR={insertSegment:NR(`insertSegment`),anchor:NR(`anchor`),relation:PR()},bR={insertSegmentFrom:AR(`persist`),anchor:NR(`anchor`),relation:PR()},xR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},SR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function CR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>c_(e,t,n,r),c=E_(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?g_(s,...n):s}}const wR=[CR(`set`,uR),CR(`set`,fR),CR(`set`,mR,[xR,SR]),CR(`set`,hR),CR(`set`,gR)],TR=[CR(`persist`,dR),CR(`persist`,pR),CR(`persist`,mR,[xR,SR]),CR(`persist`,_R),CR(`persist`,vR),CR(`persist`,yR,[],[`insertSegment`]),CR(`persist`,bR,[],[`insertSegmentFrom`])];function ER(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function DR(e){let t=ER(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function OR(e,t,n,r,i){let a=cR(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${DR(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function kR(e){let t=lR(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>oR(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function AR(e){let t=lR(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${q(o)}`)}}}function jR(e){let t=lR(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${a_(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function MR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${q(r[n])}`);return}return!0}}}function NR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=$g(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function PR(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${q(i)}`);return}return i}}}function FR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${q(i)}`);return}return i}}}function IR(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const LR={noun:`style key`,fields:{hueShift:b_(),chromaScale:b_({min:0}),lightnessScale:b_(),lightnessShift:b_()}};function RR(e,t){if(!i_(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${a_(t)}`,line:K(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:K(e.source,[`styles`,r])});continue}if(og(r)){e.issues.push({path:`styles.${r}`,message:IR(`styles.${r}`,r,`globals.endcaps`),line:K(e.source,[`styles`,r])});continue}let t=o_(e,LR,`styles.${r}`,i);t!==null&&(n[r]={...Sc,...t})}return n}const zR={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:SL(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Uk(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Hk(e,`${t}.${n}`,r[n])}}};function BR(e,t){if(!i_(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${a_(t)}`,line:K(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:K(e.source,[`presets`,r])});continue}let t=o_(e,zR,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function VR(e,t){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${a_(t)}`,line:K(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${q(i)}`,line:K(e.source,[`helpers`,r])});continue}n[r]=i}return n}const HR=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function UR(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function WR(e){let t=HR.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${UR(t)}`}function GR(e){let t=HR.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${UR(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const KR={cell:e=>`${e} sets "distribution" on a container inside a cell — everything inside a cell wears that cell's colour, so it would place nothing. Set it on the row whose children are the cells (the horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function qR(e,t){let n=new Map;for(let e of Object.keys(t)){let t=nk(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:K(e.source,[`presets`])})}function JR(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Uh(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:og(i)?IR(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:K(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:K(e.source,[`globals`,`preset`])}),qR(e,t.presets);let i=xb(t);for(let t of i.names)t!==`settings`&&!t.startsWith(ZR)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:K(e.source,[`variables`,t])});let a=(t,n,r)=>{NP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${uN}" ${NP(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),PP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${uN}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r});let i=o(t,`bar`);i!==void 0&&e.issues.push({path:n,message:KR[i](n),line:r});let a=new Map;for(let e of Cg(t)){if(e.kind!==`segment`)continue;let t=yg(e);a.set(t,[...a.get(t)??[],e])}for(let[t,i]of a){if(i.length<2)continue;let o=i[1].name,s=xg(o,new Set(a.keys()));e.issues.push({path:n,message:`${n} has ${i.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`cell`)return`cell`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||vg[e.direction]===`cell`);return vg[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:vg[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,wg(t,n)]):e.opens===void 0?[]:[[e.opens.body,Tg(t)]];function*l(e,t){for(let[n,r]of e){let e=o(n,t);e!==void 0&&(yield[e,r]),yield*l(c(n,r),s(n,t))}}let u=(n,r)=>{let a=Iy(n),o=My(n)?Object.entries(n.rows).map(([e,t])=>[t,`${r}.rows.${e}`]):c(a,r);for(let[t,n]of l(o,s(a,`bar`)))e.issues.push({path:n,message:KR[t](n),line:K(e.source,n.split(`.`))});for(let[a,o]of Ly(n,r)){let n=K(e.source,o.split(`.`));if(a.when!==void 0&&(lz(e,`${o}.when`,a.when,i,{line:n}),cz(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(AP(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${uN}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${uN}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${FI(a.name)}`,line:n}),az(e,t,a,o,n)}}};n.root!==void 0&&u(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&u(t.root,`presets.${e}.root`);let d=new Map([[`root`,Fy(t.root)]]);for(let e of Hy(t.presets)){let{node:n,path:r}=Gy(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,K(e.source,t.split(`.`)));gz(e,t,i,()=>!0)}const YR=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function XR(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=K(e.source,[`actions`,n,r]);if(!Hy(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Hy(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${FI(i)}`,line:c})},p=new Set(bg(Gy(t,a).node)),m=(r,i)=>{!PI.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${FI(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const ZR=`settings.`;function QR(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>ZR+e)])}}function $R(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:K(e.source,[`segments`,t,`settings`,n])})},a=nz(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Bg(n,tz(n)))i(e,`the defaults do not stand together: ${t}`)}function ez(e){return nz(e).length>0||Bg(e,tz(e)).length>0}function tz(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function nz(e){let t=t=>zg(rz(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||zg(rz(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${iz(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function rz(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function iz(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&zg(n)!==void 0).map(([e])=>e)}function az(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Rg(a),s=`${r}: placement "${yg(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Vg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Ph(a):``}, but it must be ${Gg(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Vg(o[e],t))||ez(o)))for(let{message:t}of Bg(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function oz(e,t,n,r,i){n.kind===`template`&&lz(e,`${t}.template`,n.template,r,{segCtx:i}),Ag(n)&&`key`in n.cache&&lz(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function sz(e,t,n,r,i){if(!(!Ag(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:K(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function cz(e,t,n,r){try{uA.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function lz(e,t,n,r,i){for(let[a,o]of pb(n,r.helpers)){if(bb(a,r))continue;if(a.startsWith(ZR)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??K(e.source,t.split(`.`))});continue}if(o!==null){uz(e,o,`Template references unknown variable ".${a}"${GR(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&bb(n,r)?` (segment-local vars are namespaced — write ".${n}")`:GR(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??K(e.source,t.split(`.`))})}}function uz(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:K(e.source,[`helpers`,t])})}function dz(e,t,n,r,i){let a=n.set,o=Dk(pv[r].configKey),s=`${a} takes ${xk(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:K(e.source,[`actions`,t,`min`])});return}let c=mz(n,i);if(c===pz){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:K(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!bk(o,e.value,i));if(l.length!==0){if(a===pv.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>og(e.value)))){let r=pv.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:IR(`actions.${t}.to`,n.to,`set: "${r}", to`),line:K(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:K(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=fz?r.join(`, `):`${r.slice(0,fz).join(`, `)} and ${r.length-fz} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:K(e.source,[`actions`,t,n])})}}}const fz=3,pz=Symbol(`any integer`);function mz(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?Qy(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:pz}function hz(e,t){return Object.entries(e).filter(([e])=>t(e))}function gz(e,t,n,r){let i=cF(t),a=Zy(i);for(let[n,o]of hz(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${eb(r,i)}`,line:K(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;_v.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:K(e.source,[`actions`,n,`set`])});let s=xv.get(o.set);s!==void 0&&dz(e,n,o,s,i)}for(let[n,i]of hz(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&GL(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:K(e.source,[`actions`,n,`do`])})});for(let[n,i]of hz(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=aA(r);if(o===null){let t=qk(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${Jk().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:K(e.source,[`actions`,n,a])});continue}let s=YR.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){XR(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Hy(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Hy(t.presets).join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Ph(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${FI(o.segment)}`,line:K(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:K(e.source,[`actions`,n,a])})}}for(let[i,a]of hz(t.variables,r)){oz(e,`variables.${i}`,a,n);let t=WR(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:K(e.source,[`variables`,i])})}for(let[i,a]of hz(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))oz(e,`segments.${i}.vars.${t}`,r,n,i);let r=Rg(a);$R(e,i,r);let o=QR(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){lz(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of _b(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){uz(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:K(e.source,[`segments`,i,n])})}}}}for(let[i,a]of hz(t.variables,r))sz(e,`variables.${i}`,a,n);for(let[i,a]of hz(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))sz(e,`segments.${i}.vars.${t}`,r,n,i)}function _z(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=vz(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:K(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function vz(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of pb(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Ag(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function yz(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function bz(e,t){return s.resolve(e,yz(t))}function xz(e,t){return typeof t==`string`&&t!==``?bz(e,t):void 0}function Sz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const Cz=new Set([`data`,`segments`,`helpers`,`actions`]),wz=`plugin.json5`,Tz=/^[a-z][a-z0-9_]*$/;function Ez(e){let t=s.basename(s.dirname(e));return Tz.test(t)?t:void 0}const Dz=`plugins.`;function Oz(e){return`${Dz}${e}.data`}function kz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Az(e)}}}function Az(e){return e instanceof Jg?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function jz(e,t){return e.map(e=>bz(s.dirname(t),e))}function Mz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=Ez(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${wz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${wz} and list that`;return o(t,a===void 0?e.config:Fz(Pz(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${Tz}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=Pz(e.config,a),u=kz(()=>{let i=p.readFileSync(n,`utf-8`),o=JF(Vz(n,a,{source:i,json:ui.default.parse(i)},t),l);return r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,Fz(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function Nz(e){let t=`${Dz}${e}.`;return e=>e.startsWith(t)}function Pz(e,t){let n=Nz(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function Fz(e,t,n){return{...e,variables:{...e.variables,[Oz(t)]:{kind:`dropped`,reason:Sz(n),definition:n.path}}}}function Iz(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Lz(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Iz)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:Sz(e)}));return t=>{let i=Iz(t);if(i===void 0)return[];let a=e.config.variables[Oz(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function Rz(e,t){let n=Hy(e.presets).flatMap(t=>[...Cg(Gy(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,zz(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Iz(t),r=n===void 0?void 0:e.variables[Oz(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>_b(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...yb(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${Oz(Iz(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function zz(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,Bz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function Bz(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function Vz(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Jg(e,a)};if(!i_(r))return a.push({path:``,message:`a plugin definition must be an object, got ${a_(r)}`}),o();for(let e of Object.keys(r))Cz.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...Cz].join(`, `)}`});let s=qz(r.data,e,i,a);if(i_(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(Lh()),groups:[]},l=aI(c,`data`,{[Oz(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!i_(t)||!i_(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=i_(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:Uz(t,Gz(t,$I(c,r.segments,new Set))),helpers:Uz(t,VR(c,r.helpers)),actions:Uz(t,Kz(t,KL(c,r.actions)))};for(let[e,t]of Hz(u))try{uA.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*Hz(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function Uz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${Dz}${e}.${t}`,n]))}function Wz(e,t){return`${Dz}${e}.${t}`}function Gz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,n.kind===`state`?{...n,key:Wz(e,n.key)}:n]))}]))}function Kz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Wz(e,n.set)}:n]))}function qz(e,t,n,r){if(typeof e==`string`&&e!==``)return bz(s.dirname(t),e);if(i_(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(i_(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function Jz(e){let t=[...[...(process.env.XDG_DATA_DIRS||Zz()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),Yz(),...e===null?[]:[s.join(e,Xz)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function Yz(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const Xz=s.join(`.cc-candybar`,`plugins`);function Zz(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function Qz(e){let t=Jz(e),n=new Map,r=[],i=[];for(let e of t){let t=$z(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,wz));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${wz}: move this file to ${s.join(e,`<name>`,wz)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function $z(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||eB(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function eB(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function tB(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const nB=[`json5`,`json`];function rB(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?nB.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...nB.map(e=>s.join(r,`.cc-candybar.${e}`)),...nB.map(e=>`${iB()}.${e}`)])]}function iB(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function aB(e,t,n){let r=[],i=new Map;for(let a of rB(e,t,n)){let e=tB(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:oB(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function oB(e){let t=iB();return e.find(e=>nB.some(n=>e===`${t}.${n}`))??`${t}.${nB[0]}`}function sB(e,t,n){let r=aB(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function cB(e){return lB(e).join(`
|
|
185
|
+
`)||null}function lB(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function uB(e,t){let n=rB(e,t).filter(e=>tB(e)===`present`),r=new Map;for(let e of n){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),i=s.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function dB(e,t,n,r){return e===null?{...xB,config:JF(xB.raw,t)}:pB(e,p.readFileSync(e,`utf-8`),t,n,r)}const fB={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function pB(e,t,n,r,i){let a=wB(e,t,i,(t,a)=>{let o=Mz(jz(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>yB(t,n,r,e,i)),s=Lz(o,r.beneath.dropped);return{inherited:new Set([...QI(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=Rz(JF(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(Sz)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const mB=new WeakMap;function hB(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,_B(e)])]),a=mB.get(n)??new Map;mB.set(n,a);let o=JSON.stringify([t.projectDir,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=Mz(e,t,{config:n,rendering:new Map},(e,t,n)=>yB(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function gB(e,t,n){return Mz(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>yB(e,t,n,`<plugin install>`,void 0)).dropped}function _B(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function vB(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:AD(r.cwd)},s=Qz(o.projectDir),c=hB(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=pB(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(Sz));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:SB(dB(null,u,fB),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:SB(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),SB(e,e.path,a);throw n.entered(v.path),e}}function yB(e,t,n,r,i){if(n){SB(bB(e),r,i);return}let a=Nz(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(gz(s,e,xb(e),a),_z(s,e,a),o.length>0)throw new Jg(r,o)}function bB(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const xB={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function SB({config:e,raw:t,source:n},r=`<config>`,i=new Set(Lh())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(JR(o,e,t),_z(o,e),a.length>0)throw new Jg(r,a);let s=HL(e,a);if(a.length>0)throw new Jg(r,a);return EF(KP(s))}function CB(e,t,n=new Set(Lh()),r=TB){return wB(e,t,n,()=>({inherited:r,layer:null})).raw}function wB(e,t,n,r){let i=EB(e,t),a=Zg(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Lh()),groups:[]};if(!i_(i))throw new Jg(e,[{path:``,message:`Config root must be an object, got ${a_(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:kB({...c,issues:[]},i.plugins)??[],i_(i.segments)?Object.keys(i.segments):[]),d=DB(c,i,l);if(s.length>0)throw new Jg(e,s,o);return{raw:d,warnings:o,layer:u}}const TB=new Set;function EB(e,t){try{return ui.default.parse(t)}catch(t){let n=t;throw new Jg(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function DB(e,t,n){for(let n of Object.keys(t))OB.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...OB].join(`, `)}`,line:K(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Vk(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=aI(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=$I(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
186
186
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
187
187
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
188
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:K(e.source,[`layout`])}),t.root!==void 0&&(r.root=gL(e,`root`,t.root)),t.actions!==void 0&&(r.actions=BL(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:K(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=MR(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Pk(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=PR(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Rk(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=FR(e,t.helpers)),t.plugins!==void 0&&(r.plugins=SB(e,t.plugins)),wL(e,r),PL(e,r),_A(e,r),rk(e,r,X,`the global settings menu`),r}const xB=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function SB(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${$g(t)}`,line:K(e.source,[`plugins`])})}const CB={},wB=XM(`commands.`),TB=nN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),EB=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,DB=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${EB}) (basename .project_dir) (ne (${EB}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,OB=`{{ ${KA} }}`,kB={min:0,max:100,step:5},AB={warnAt:{label:`warning at %`,domain:kB,default:50},errorAt:{label:`error at %`,domain:{...kB,atLeast:`warnAt`},default:80}};function jB(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:kB,default:80}}}const MB={globals:{palette:`tokyo-night`},variables:{...wB.variables,...KO,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:DB},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:OB,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:zM(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:wB.template,when:wB.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:jB(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:jB(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:AB,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:AB,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${eh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:TB.template,bg:TB.bg,when:TB.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...zM(``).actions,...wB.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...TB.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:CB,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${eh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${KA}) 2 (readableOn (color "accent") (bgOf) ${eh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${eh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:rN(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},NB=new Set([MB.globals.palette,...Object.keys(MB.themeDefaults),...Object.values(MB.segments).map(e=>e.palette)].filter(e=>e!==void 0)),PB=HF(gB(`<default>`,JSON.stringify(MB),NB),MB),FB=Iy(PB.presets);function IB(e){return FB.includes(e)}const LB=Object.freeze({});function RB(e,t){return e.kind===`decided`?t[e.name]??LB:LB}function zB(e,t){return{...e,...Object.fromEntries(ev.map(n=>[n,e[n]??t[n]]))}}const BB=e=>j_(t=>e[T_[t].setting]);function VB(e,t,n,r){let i=nv(e);return Ah(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function HB(e,t,n){let r=Ly(t(`preset`),e.globals.preset,e.presets),i=By(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=xy(a.palette,t(`theme`),i.palette),s=zB(i,RB(o,e.themeDefaults));return{...Object.fromEntries(Q_.map(e=>[e,VB(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Uh(a.style,t(`style`),s.style,e.styles),effect:Zh(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function UB(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?ag:og;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const WB=Object.entries(sv),GB=new Set(lv.map(e=>e.sessionKey)),KB=()=>!1;function qB(e,t){return HB(e,e=>GB.has(e)?t(e):null,KB)}const JB=[`preset`,`theme`];function YB(e,t,n){let r=new Set(JB.slice(0,n).map(e=>sv[e].sessionKey));return HB(e,e=>r.has(e)?t(e):null,KB)}function XB(e,t){let n=Array.from({length:JB.length+1},(n,r)=>YB(e,t,r));return e=>{let t=JB.indexOf(e);return n[t===-1?JB.length:t]}}function ZB(e,t,n,r){return e.flatMap(([e,i])=>{let a=UB(t,e);return a===null||a===UB(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function QB(e,t,n){return UB(qB(e,t),n)}function $B(e,t){let n=qB(e,t);return ZB(WB,n,XB(e,t),t=>eV(e,n.preset,t.configKey))}function eV(e,t,n){return n in(Ry(e.presets,t).globals??{})?Qk(t,n):n}function tV(e,t,n){let r=Ly(t(sv.preset.sessionKey),e.globals.preset,e.presets),i=$k(n);return{key:i?.scope===`globals`?eV(e,r,i.field):n,globals:By(e,r)}}function nV(e,t){let{preset:n}=qB(e,t);return aV(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Lg(a,s);return c===void 0||Ig(c)===Ig(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function rV(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Iy(e.presets).flatMap(n=>{let i=aV(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return Pg(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:Lg(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const iV=new WeakMap;function aV(e,t){let n=iV.get(e)??new Map;iV.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[..._g(zy(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Mg(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function oV(e,t){let n=qB(e,t);return{from:n.preset,globals:Ry(e.presets,n.preset).globals??{},picks:ZB(WB.filter(([e])=>e!==`preset`),n,XB(e,t),e=>e.configKey),placements:nV(e,t)}}function sV(e,t){return HB({...e,globals:{palette:t},presets:{}},()=>null,KB)}function cV(e,t){let n=qB(e,t),r=UB(n,`theme`);if(r===null)return{kind:`rule`};let i=sV(e,r),a=By(e,n.preset),o=Object.fromEntries(ev.map(e=>[e,UB(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:ev.some(e=>o[e]!==UB(i,e))}}function lV(e){return{sessionKeys:lv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Ak(e)?FB.map(t=>Qk(t,e)):[],...Zk(e)?jh().map(t=>Xk(t,e)):[]]}}function uV(e){return new Set(lv.map(e=>e.configKey).filter(t=>lV(t).fileKeys.some(t=>pV(e,fV(t)))))}function dV(e,t,n){let r=$B(e,n),i=new Set(r.map(e=>e.configKey)),a=mv(e=>i.has(sv[e].configKey)||t.has(sv[e].configKey)),o=cV(e,n);return{unsaved:r.length+nV(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function fV(e){let t=$k(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return eA(t)}function pV(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&pV(e[n],r)}const mV=jh(),hV=new Set(mV),gV=new Set(Qh),_V=e=>e?hV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${mV.join(`, `)})`}:{ok:!1,reason:`theme name is required`},vV=e=>e?gV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Qh.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},yV=new Set([`1`,`true`]),bV=new Set([`0`,`false`]),xV={endcaps:vV,theme:_V,"toolbar-expanded":e=>yV.has(e)?{ok:!0,value:`1`}:bV.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},SV=NF(xV,`state`,kV);function CV(e,t){return SV.register(e,t)}function wV(e){return SV.gateFor(e)}function TV(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:Ky(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function EV(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(xV,e.key))}function DV(e,t,n){let r=hv.get(n);if(r!==void 0)return QB(e,t,r);for(let[,t]of Og(e))if(t.key===n)return t.default??null;return null}function OV(e){let t=nF(e);return EV(Object.values(e.actions).flatMap(e=>TV(e,t)))}function kV(e){return jF(OV(e))}const AV=`update.dismissed`,jV=`updateNotice`,MV=sv.updateNotice.sessionKey;function NV(e){return e.kind===`source`?e.newer.digest:La(e.newer)}const PV=e=>`${e.version} [${Ke(e.digest)}]`;function FV(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:PV(e.newer),running:PV(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:La(e.newer),running:La(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${za}@${La(e.newer)}`,`install`]}}}}const IV={kind:`idle`},LV={kind:`running`};function RV(e,t,n){if(e===null)return[];let r=NV(e);if(!n.enabled||n.dismissed===r)return[];let i=FV(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
189
|
-
`),c=Hr([{verb:br,args:[s]}]),l=t.kind===`running`?
|
|
190
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:ZV(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const eH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function tH(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?eH[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const nH={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},rH=Object.keys(nH);function iH(e,t){let n=tH(t.color),r=tH(t.bgcolor),i={};for(let e of rH){if(t[e]!==!0)continue;let n=nH[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const aH=new H;function oH(e){return{ok:!0,band:new Kf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(iH(t.slice(r,i.start),aH)),n.push(iH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(iH(t.slice(r),aH)),n})}}function sH(e){let t=$V(pn(e)).output;try{return oH(t)}catch(e){return oH(`${xv}${bv}⚠ cc-candybar ${vv(e instanceof Error?e.message:String(e))}${Sv}\n`)}}function cH(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const lH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function uH(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:lH[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const dH={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},fH=Object.keys(dH);function pH(e){return e.replaceAll(`#`,`##`)}function mH(e){let t=fH.filter(t=>e[t]===!0).map(e=>{let t=dH[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${uH(e.color)}`,`bg=${uH(e.bgcolor)}`,...t].join(`,`)}]`}const hH=new H;function gH(e){let t={},n=(e,n)=>{let r=mH(n)+pH(e);if(n.link===void 0)return r;let i=cH(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new Kf().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),hH)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),hH)),r.join(``)}),links:t}}function _H(e){let t=$V(pn(e)).output;try{return gH(t)}catch(e){return gH(`${xv}${bv}⚠ cc-candybar ${vv(e instanceof Error?e.message:String(e))}${Sv}\n`)}}const vH={band:e=>JSON.stringify(sH(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:_H(e)})};var yH=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const bH={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var xH=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await yH.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await yH.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(bH).length} models`),this.executionCache=bH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(bH).length} models`),bH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const SH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function CH(e){if(typeof e==`string`)return SH.exec(e)?.[1]}function wH(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function TH(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function EH(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=wH(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?CH(TH(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function DH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function OH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function kH(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=LH(i,t,s.value);let c=PH(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function AH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(MH(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=TH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||jH.test(r)?`claude-code`:`prompt`}const jH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function MH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function NH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=AH(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:EH(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function PH(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function FH(e){let t=PH(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return NH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function IH(e){let t=[];for(let n of e.split(`
|
|
191
|
-
`)){let e=FH(n);e&&t.push(e)}return t}function LH(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function RH(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function zH(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=LH(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>IH(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}var BH=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function VH(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const HH=new Map,UH={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},WH={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function GH(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function KH(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function qH(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const JH={entries:0,cost:0,breakdown:qH(),days:new Map};async function YH(e,t){let n=GH(new Date(KH())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await xH.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=GH(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...UH};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function XH(e){let t=0,n=0,r=qH(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...UH};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:WH,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function ZH(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var QH=class{sessions=new Map;flight=new BH;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new BH;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:WH,i=t?.cost?.total_cost_usd??null;return F({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=GH(vO(n)),i=DH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return L(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...UH},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??HH:HH;c||=a.has(r);let l=a.get(r)??UH;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?F({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):I}async observeSpeed(e,t,n){if(!e)return I;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=VH(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),F({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return I;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,F(a);if(!t)return a?F(a):I;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),F(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await kH(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of RH(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await zH(e,r,JH,YH);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of RH(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...XH(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=KH(),i=await OH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await ZH(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},$H=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await zH(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of RH(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function eU(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var tU=class{fold;constructor(e={}){this.fold=new $H(void 0,eU,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return L(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),I):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),F({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const nU={messageCount:0,nonPrompts:0,recent:[]},rU=new Set([`turn`,`interrupt`,`claude-code`]);function iU(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!rU.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function aU(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var oU=class{fold;constructor(e={}){this.fold=new $H(nU,iU,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:aU(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const sU={command:null,todos:[],pending:[],done:[]};function cU(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function lU(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function uU(e,t){if(t.isSidechain)return e;let n=lU(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=cU(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function dU(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>cU(e,t.name),[]),done:e.done}}var fU=class{fold;constructor(e={}){this.fold=new $H(sU,uU,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`activity (${e}): ${n.reason}`):F(dU(n.value))}};function pU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function mU(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function hU(e,t,n,r){return mU(ut(pU(e,t,n,r)),n)}async function gU(e,t,n,r){return mU(await lt(pU(e,t,n,r)),n)}const _U=e=>`${e.socket}\n${e.pane}`;var vU=class{names=new Map;asking=new BH;constructor(e=Date.now){this.now=e}getSessionName(e){let t=_U(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await gU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?F(r):I:L(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const yU=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var bU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=yU(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=yU(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function xU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const SU=s.join(`lib`,`ceiling_config.py`),CU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function wU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function TU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return L(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return F(n)}function EU(e,t){if(!p.existsSync(e))return I;let n;try{n=wU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return L(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return I;let i=TU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return I;let a=[SU,CU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?F(r.installPath):L(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function DU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function OU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function kU(e){let t;try{t=JSON.parse(e)}catch{return L(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?F({ceiling:i,session:r}):L(`memento read: unexpected answer: ${e.trim()}`)}async function AU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
|
|
188
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:K(e.source,[`layout`])}),t.root!==void 0&&(r.root=SL(e,`root`,t.root)),t.actions!==void 0&&(r.actions=KL(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:K(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=RR(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Bk(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=BR(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Wk(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=VR(e,t.helpers)),t.plugins!==void 0&&(r.plugins=kB(e,t.plugins)),AL(e,r),BL(e,r),CA(e,r),lk(e,r,X,`the global settings menu`),r}const OB=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function kB(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${a_(t)}`,line:K(e.source,[`plugins`])})}const AB={},jB=nN(`commands.`),MB=cN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),NB=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,PB=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${NB}) (basename .project_dir) (ne (${NB}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,FB=`{{ ${QA} }}`,IB={min:0,max:100,step:5},LB={warnAt:{label:`warning at %`,domain:IB,default:50},errorAt:{label:`error at %`,domain:{...IB,atLeast:`warnAt`},default:80}};function RB(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:IB,default:80}}}const zB={globals:{palette:`tokyo-night`},variables:{...jB.variables,...QO,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:PB},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:FB,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:GM(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:jB.template,when:jB.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:RB(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:RB(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:LB,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:LB,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${eh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:MB.template,bg:MB.bg,when:MB.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...GM(``).actions,...jB.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...MB.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:AB,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${eh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${QA}) 2 (readableOn (color "accent") (bgOf) ${eh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${eh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:lN(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},BB=new Set([zB.globals.palette,...Object.keys(zB.themeDefaults),...Object.values(zB.segments).map(e=>e.palette)].filter(e=>e!==void 0)),VB=JF(CB(`<default>`,JSON.stringify(zB),BB),zB),HB=Hy(VB.presets);function UB(e){return HB.includes(e)}const WB=Object.freeze({});function GB(e,t){return e.kind===`decided`?t[e.name]??WB:WB}function KB(e,t){return{...e,...Object.fromEntries(ov.map(n=>[n,e[n]??t[n]]))}}const qB=e=>L_(t=>e[j_[t].setting]);function JB(e,t,n,r){let i=cv(e);return Ih(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function YB(e,t,n){let r=Uy(t(`preset`),e.globals.preset,e.presets),i=Ky(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Dy(a.palette,t(`theme`),i.palette),s=KB(i,GB(o,e.themeDefaults));return{...Object.fromEntries(iv.map(e=>[e,JB(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yh(a.style,t(`style`),s.style,e.styles),effect:rg(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function XB(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?dg:fg;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const ZB=Object.entries(pv),QB=new Set(hv.map(e=>e.sessionKey)),$B=()=>!1;function eV(e,t){return YB(e,e=>QB.has(e)?t(e):null,$B)}const tV=[`preset`,`theme`];function nV(e,t,n){let r=new Set(tV.slice(0,n).map(e=>pv[e].sessionKey));return YB(e,e=>r.has(e)?t(e):null,$B)}function rV(e,t){let n=Array.from({length:tV.length+1},(n,r)=>nV(e,t,r));return e=>{let t=tV.indexOf(e);return n[t===-1?tV.length:t]}}function iV(e,t,n,r){return e.flatMap(([e,i])=>{let a=XB(t,e);return a===null||a===XB(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function aV(e,t,n){return XB(eV(e,t),n)}function oV(e,t){let n=eV(e,t);return iV(ZB,n,rV(e,t),t=>sV(e,n.preset,t.configKey))}function sV(e,t,n){return n in(Wy(e.presets,t).globals??{})?iA(t,n):n}function cV(e,t,n){let r=Uy(t(pv.preset.sessionKey),e.globals.preset,e.presets),i=aA(n);return{key:i?.scope===`globals`?sV(e,r,i.field):n,globals:Ky(e,r)}}function lV(e,t){let{preset:n}=eV(e,t);return fV(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ug(a,s);return c===void 0||Hg(c)===Hg(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function uV(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Hy(e.presets).flatMap(n=>{let i=fV(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return Bg(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:Ug(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const dV=new WeakMap;function fV(e,t){let n=dV.get(e)??new Map;dV.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Cg(Gy(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Rg(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function pV(e,t){let n=eV(e,t);return{from:n.preset,globals:Wy(e.presets,n.preset).globals??{},picks:iV(ZB.filter(([e])=>e!==`preset`),n,rV(e,t),e=>e.configKey),placements:lV(e,t)}}function mV(e,t){return YB({...e,globals:{palette:t},presets:{}},()=>null,$B)}function hV(e,t){let n=eV(e,t),r=XB(n,`theme`);if(r===null)return{kind:`rule`};let i=mV(e,r),a=Ky(e,n.preset),o=Object.fromEntries(ov.map(e=>[e,XB(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:ov.some(e=>o[e]!==XB(i,e))}}function gV(e){return{sessionKeys:hv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Ik(e)?HB.map(t=>iA(t,e)):[],...rA(e)?Lh().map(t=>nA(t,e)):[]]}}function _V(e){return new Set(hv.map(e=>e.configKey).filter(t=>gV(t).fileKeys.some(t=>bV(e,yV(t)))))}function vV(e,t,n){let r=oV(e,n),i=new Set(r.map(e=>e.configKey)),a=bv(e=>i.has(pv[e].configKey)||t.has(pv[e].configKey)),o=hV(e,n);return{unsaved:r.length+lV(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function yV(e){let t=aA(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return oA(t)}function bV(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&bV(e[n],r)}const xV=Lh(),SV=new Set(xV),CV=new Set(ig),wV=e=>e?SV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${xV.join(`, `)})`}:{ok:!1,reason:`theme name is required`},TV=e=>e?CV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${ig.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},EV=new Set([`1`,`true`]),DV=new Set([`0`,`false`]),OV={endcaps:TV,theme:wV,"toolbar-expanded":e=>EV.has(e)?{ok:!0,value:`1`}:DV.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},kV=zF(OV,`state`,IV);function AV(e,t){return kV.register(e,t)}function jV(e){return kV.gateFor(e)}function MV(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:Qy(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function NV(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(OV,e.key))}function PV(e,t,n){let r=xv.get(n);if(r!==void 0)return aV(e,t,r);for(let[,t]of Pg(e))if(t.key===n)return t.default??null;return null}function FV(e){let t=cF(e);return NV(Object.values(e.actions).flatMap(e=>MV(e,t)))}function IV(e){return LF(FV(e))}const LV=`update.dismissed`,RV=`updateNotice`,zV=pv.updateNotice.sessionKey;function BV(e){return e.kind===`source`?e.newer.digest:La(e.newer)}const VV=e=>`${e.version} [${Ke(e.digest)}]`;function HV(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:VV(e.newer),running:VV(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:La(e.newer),running:La(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${za}@${La(e.newer)}`,`install`]}}}}const UV={kind:`idle`},WV={kind:`running`};function GV(e,t,n){if(e===null)return[];let r=BV(e);if(!n.enabled||n.dismissed===r)return[];let i=HV(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
189
|
+
`),c=Hr([{verb:br,args:[s]}]),l=t.kind===`running`?ly(`[${i.busy}]`,c):ly(`[${i.act}]`,Hr([{verb:Nr,args:[n.sessionId]}]));return[{severity:sy,message:s,lines:[[ly(a,c),l,ly(`[dismiss]`,Hr([{verb:mr,args:[n.sessionId,LV,r]}])),ly(`[disable]`,Hr([{verb:xr,args:[n.sessionId,RV,`false`]},{verb:mr,args:[n.sessionId,zV,`false`]}]))],...o.map(e=>[ly(e,c)])]}]}function KV(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function qV(e){switch(e.kind){case`current`:return[`info`,`build: current ${VV(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${VV(e.source)}, running ${VV(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function JV(e){switch(e.kind){case`current`:return[`info`,`release: current ${La(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${La(e.latest)}, running ${La(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${La(e.installed)}, latest ${La(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function YV(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const XV=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function ZV(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=XV(e.stderr)??e.error??XV(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function QV(){let e=[VF(RV,[`false`]),AV(zV,[`false`]),AV(LV,[])];return()=>e.forEach(e=>e())}function $V(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=UV,d=null,f=YV(s),p=YV(s),m=()=>KV(c,l);function h(){let e=m(),t=e===null?null:BV(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:AV(LV,[t])})}function g(){c=Qe(t,Ye),f(qV(c)),h()}async function _(){l=Va(qe,await Ba(za,a,i)),p(JV(l)),h()}return{arm(){QV(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>GV(m(),u,e),act(){let e=m();if(e===null)throw new J(`apply-update: nothing newer is known to apply`);let t=HV(e);if(u.kind===`running`)throw new J(`apply-update: already ${t.busy}`);u=WV,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),lt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=UV,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=ZV(n);u={kind:`failed`,identity:BV(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function eH(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function tH(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function nH(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:eH(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=eH(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!tH(t,n)){a(`info`,`binary ${n.kind===`absent`?`gone`:`changed`} (${e}); shutting down`),c&&clearInterval(c),i();return}}};return{arm(){for(let{path:e,stamp:t}of o)t.kind===`failed`&&a(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);c=setInterval(l,n),c.unref()},checkNow:l}}const rH=`${Dv}${Ev}`;function iH(e){return`${rH}⚠ cc-candybar: ${aH(e)}${Ov}\n`}function aH(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${Tv(e.message,60)}`;case`render_failed`:return`render failed: ${Tv(e.message,60)}`;case`switched_off`:return`switched off: ${Tv(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Tv(e.message,60)}`}}function oH(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
190
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:iH(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const sH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function cH(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?sH[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const lH={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},uH=Object.keys(lH);function dH(e,t){let n=cH(t.color),r=cH(t.bgcolor),i={};for(let e of uH){if(t[e]!==!0)continue;let n=lH[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const fH=new H;function pH(e){return{ok:!0,band:new qf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(dH(t.slice(r,i.start),fH)),n.push(dH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(dH(t.slice(r),fH)),n})}}function mH(e){let t=oH(pn(e)).output;try{return pH(t)}catch(e){return pH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}function hH(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const gH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function _H(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:gH[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const vH={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},yH=Object.keys(vH);function bH(e){return e.replaceAll(`#`,`##`)}function xH(e){let t=yH.filter(t=>e[t]===!0).map(e=>{let t=vH[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${_H(e.color)}`,`bg=${_H(e.bgcolor)}`,...t].join(`,`)}]`}const SH=new H;function CH(e){let t={},n=(e,n)=>{let r=xH(n)+bH(e);if(n.link===void 0)return r;let i=hH(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new qf().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),SH)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),SH)),r.join(``)}),links:t}}function wH(e){let t=oH(pn(e)).output;try{return CH(t)}catch(e){return CH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}const TH={band:e=>JSON.stringify(mH(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:wH(e)})};var EH=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const DH={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var OH=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await EH.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await EH.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(DH).length} models`),this.executionCache=DH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(DH).length} models`),DH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const kH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function AH(e){if(typeof e==`string`)return kH.exec(e)?.[1]}function jH(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function MH(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function NH(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=jH(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?AH(MH(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function PH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function FH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function IH(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=WH(i,t,s.value);let c=VH(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function LH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(zH(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=MH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||RH.test(r)?`claude-code`:`prompt`}const RH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function zH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function BH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=LH(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:NH(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function VH(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function HH(e){let t=VH(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return BH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function UH(e){let t=[];for(let n of e.split(`
|
|
191
|
+
`)){let e=HH(n);e&&t.push(e)}return t}function WH(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function GH(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function KH(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=WH(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>UH(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}var qH=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function JH(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const YH=new Map,XH={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},ZH={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function QH(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function $H(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function eU(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const tU={entries:0,cost:0,breakdown:eU(),days:new Map};async function nU(e,t){let n=QH(new Date($H())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await OH.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=QH(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...XH};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function rU(e){let t=0,n=0,r=eU(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...XH};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:ZH,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function iU(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var aU=class{sessions=new Map;flight=new qH;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new qH;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:ZH,i=t?.cost?.total_cost_usd??null;return F({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=QH(wO(n)),i=PH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return L(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...XH},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??YH:YH;c||=a.has(r);let l=a.get(r)??XH;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?F({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):I}async observeSpeed(e,t,n){if(!e)return I;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=JH(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),F({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return I;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,F(a);if(!t)return a?F(a):I;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),F(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await IH(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of GH(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await KH(e,r,tU,nU);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of GH(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...rU(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=$H(),i=await FH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await iU(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},oU=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await KH(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of GH(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function sU(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var cU=class{fold;constructor(e={}){this.fold=new oU(void 0,sU,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return L(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),I):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),F({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const lU={messageCount:0,nonPrompts:0,recent:[]},uU=new Set([`turn`,`interrupt`,`claude-code`]);function dU(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!uU.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function fU(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var pU=class{fold;constructor(e={}){this.fold=new oU(lU,dU,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:fU(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const mU={command:null,todos:[],pending:[],done:[]};function hU(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function gU(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function _U(e,t){if(t.isSidechain)return e;let n=gU(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=hU(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function vU(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>hU(e,t.name),[]),done:e.done}}var yU=class{fold;constructor(e={}){this.fold=new oU(mU,_U,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`activity (${e}): ${n.reason}`):F(vU(n.value))}};function bU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function xU(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function SU(e,t,n,r){return xU(ut(bU(e,t,n,r)),n)}async function CU(e,t,n,r){return xU(await lt(bU(e,t,n,r)),n)}const wU=e=>`${e.socket}\n${e.pane}`;var TU=class{names=new Map;asking=new qH;constructor(e=Date.now){this.now=e}getSessionName(e){let t=wU(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await CU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?F(r):I:L(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const EU=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var DU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=EU(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=EU(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function OU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const kU=s.join(`lib`,`ceiling_config.py`),AU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function jU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function MU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return L(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return F(n)}function NU(e,t){if(!p.existsSync(e))return I;let n;try{n=jU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return L(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return I;let i=MU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return I;let a=[kU,AU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?F(r.installPath):L(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function PU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function FU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function IU(e){let t;try{t=JSON.parse(e)}catch{return L(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?F({ceiling:i,session:r}):L(`memento read: unexpected answer: ${e.trim()}`)}async function LU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
|
|
192
192
|
import json, math, sys
|
|
193
193
|
sys.path.insert(0, sys.argv[1])
|
|
194
194
|
from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
|
|
@@ -197,18 +197,18 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
|
|
|
197
197
|
layer = ceiling_in(directory / CONFIG_NAME)
|
|
198
198
|
print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
|
|
199
199
|
"session": layer.text if layer else None}))
|
|
200
|
-
`,s.join(e,`lib`),t.sessionId,t.cwd],env:
|
|
201
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!
|
|
202
|
-
`).at(-1).trim();function
|
|
203
|
-
`).map(e=>Zo(e.replace(
|
|
204
|
-
`);if(i.length>1)return n();let a=Math.max(0,t.width-OW(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];xW(c,c.cellLength+a,n)}),n()}function AW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=jW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Dv(a.style)};if(e.style.link){i();let r=jW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function jW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>MW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function MW(e,t){let n=e.copy();return n.style=t,n}function NW(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function PW(e,t){let{look:n}=NW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function FW(e,t){let{layout:n}=NW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function IW(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function LW(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,RW(e,t,o,n,r,i));return i}function RW(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Ky(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=fv.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Ky(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Ky(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:VW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:VW(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:RL(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:VW(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function zW(e){return e.kind===`do`?zW(e.head):e}function BW(e){switch(zW(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function VW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function HW(e,t){return e.has(t)?wb(e.read(t)):``}function UW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function WW(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function GW(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Dv(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Dv(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function KW(e,t){return Math.max(e.members.indexOf(HW(t,e.stateVar)),0)}function qW(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=HW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=HW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=HW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(KW(e,r)+1)%e.members.length];return{effects:[{verb:mr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:hr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:gr,args:[UW(e.text,vD(r))]}],active:!1};case`open`:return{effects:[{verb:_r,args:[UW(e.target,vD(r))]}],active:!1};case`persist-literal`:{let t=HW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=HW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(KW(e,r)+1)%e.members.length];return{effects:[{verb:xr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Sr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Dr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`back`:return{effects:[{verb:jr,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:Mr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Tr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Er,args:[i,UW(e.name,vD(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Pr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ir,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Rr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:zr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Or,args:[i,e.key,xF(e.op)]}],active:!1};case`do`:{let a=qW(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>qW(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Or,args:[i,e.key,xF(r)]}],active:!1}}}}function JW(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,KW(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function YW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=NW(n,`action "${e}"`).store,{display:a,boundValue:o}=JW(e,zW(r),t,i),s=HW(i,`session.id`),{effects:c,active:l}=qW(r,a.plain,o,i,s);return GW(a,Hr(c),l)}function XW(e){return{action:{fn:(t,...n)=>YW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function ZW(e,t){return WW(`✕`,Hr([{verb:mr,args:[HW(e,`session.id`),t,P]}]),!1)}function QW(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(th(e,t,n))})}function $W({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function eG(e,t,n){return new H({color:B.fromRgba(Uc(Gm(e,`warning`),t,eh,n))})}function tG(e,t,n){return H.combine([QW(e,t,n),eG(e,t,n)])}function nG(e,t,n){return QW(e.palette,Sh(e.palette,e.disclosure,[t],n),n)}function rG(e){let t=B.fromRgba(Gm(e,`background`)),n=G.fromFragments(vm.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Gm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const iG=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},aG=e=>new H({bold:e});function oG(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>iG(a,H.combine([nG(e,{...n,distribution:t},i),aG(o)]));let o=QW(e.palette,a,i);return(e,t,i,a)=>sG(i,H.combine([o,aG(a)]),r(t,n))}const sG=(e,t,n)=>iG(G.fromFragments([iG(e,t),iG(` `,t),rG(n)]));function cG(e,t){return t===void 0?(e,t,n)=>iG(n):(n,r,i)=>sG(i,void 0,t(r,e))}function lG(e,t,n,r,i){let a=QW(e.palette,i,r);return(e,r,i,o)=>iG(G.fromFragments([iG(o?`[`:` `,a),rG(n(r,t)),iG(o?`]`:` `,a)]))}function uG(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>dG(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function dG(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function fG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function pG(e){return{current:null,drawnAt:e}}function mG(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function hG(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function gG(e){return new G(e).cellLength}function _G(e){let{width:t,chromeCols:n,padding:r}=NW(e,`a row fit`);return Math.max(1,t-n-2*r)}function vG(e){let{padding:t,seamCols:n}=NW(e,`a row fit`);return Math.max(1,_G(e)-(gG(`✕`)+2*t+n))}function yG(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function bG(e,t,n){let r=gG(`←`)+1+gG(`→`)+1,i=yG(e,t,n);return(i.length>1?yG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function xG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function SG(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function CG(e,t,n){let r=e.compiled.get(t),i=r&&zW(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function wG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=NW(a,`picker`).store,d=HW(u,`session.id`),f=`stateVar`in t?HW(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?vG(a):_G(a):1/0,h=(r.kind===`led`?0:gG(`✕`)+1)+c.reduce((e,t)=>e+gG(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?bG(_.map(e=>e.cellLength),m,h):uG(g.entries,g.groups,i),y=parseInt(HW(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>Hr([{verb:mr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:mr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Hr([...qW(l,e,e,u,d).effects,...C]),ie=(e,n)=>GW(e,re(t.options[n])),ae=r.kind===`led`?[]:[WW(`✕`,Hr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>WW(e,Hr([...qW(l,r,r,u,d).effects,{verb:mr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(WW(`←`,te(x-1),!1));let w=x<v.length-1?[WW(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[xG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[xG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(xG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>gG(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:vv(a),s=` `.repeat(n-gG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(xG([ie(p(r,fG(c,m)),r)],i))}}return se}function TG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{fD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=SG(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=CG(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=hG(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=wG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,oG(u,Nm(void 0),PW(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),eG(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function EG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function DG(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function OG(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=NW(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=HW(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return xG([],!0);let d=HW(o,t.stateVar),f=EG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Hr(qW(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=GW(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):GW(cG(PW(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Hr(qW(n.compiled.get(a),p(0),void 0,o,c).effects)),b=DG(e=>v(e).cellLength,u,gG(`◀`)+1+y.cellLength+1+gG(`▶`),vG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return xG([...ee(-1).reverse(),WW(`◀`,h(-1),!1),y,WW(`▶`,h(1),!1),...ee(1)],!0)}function kG(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(fD(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&BW(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=CG(e,n,`carousel`),l=hG(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return OG(n,c,e,oG(l,Nm(void 0),PW(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function AG(e,t,n){let r=CG(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function jG(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function MG(e,t,n,r){let i=AG(e,t,n),a=r??HW(NW(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,PW(e,`{{ ${n} }}`))}function NG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(fD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return rG(MG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=AG(e,r,`swatches`),o=SG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=hG(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=wG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,lG(s,PW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),eG(s.palette,s.bg,c),u===0?[]:(()=>{let t=EG(l,HW(NW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[jG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const PG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function FG(e,t,n,r){let i=ph(e,n,r),a=(t,n)=>({text:t,colour:n,ink:th(e,n,r)});return[[Om(t).map((n,i)=>{let a=Km(e,n);return{text:PG[i%PG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Gm(e,`warning`)),a(`error`,Gm(e,`error`))]]]}function IG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:$W({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function LG(e,t,n,r,i){let a=FG(e,t,n,r).map(e=>IG(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
205
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
206
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
200
|
+
`,s.join(e,`lib`),t.sessionId,t.cwd],env:PU(t),timeoutMs:3e3,category:`memento.read`});return n.ok?IU(n.stdout):L(FU(n))}function RU(e,t,n){let r=ut({bin:s.join(e,AU),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:PU(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(FU(r))}function zU(e,t){return NU(Ca(e),t)}function BU(){return{locate:e=>zU(e.claudeConfigDir,e.projectDir),read:LU,move:RU}}function VU(e){return{gitProvider:new vO({watchers:e.watchers,logger:e.logger}),usageStore:new aU({logger:e.logger}),contextProvider:new cU({logger:e.logger}),metricsProvider:new pU({logger:e.logger}),activityProvider:new yU({logger:e.logger}),tmuxService:new TU,mementoProvider:new DU(BU()),autoCompact:oN,log:e.logger}}const HU=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function UU(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function WU(e){let t=await GU(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function GU(e){for(let t of[65536,1048576]){let n=await _a(e,t);if(n.kind!==`ok`)return n;let r=KU(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function KU(e,t){let n=e.toString(`utf8`).split(`
|
|
201
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!HU.test(t))continue;let r=UU(t);if(r!=null)return r}return null}function qU(e,t,n){return Me({dir:e.project_dir,env:n===void 0?[]:[[ya,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function JU(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function YU(e){return{...Object.fromEntries(iv.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:UB(e.preset)}}}const XU={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function ZU(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const QU=10*1e3;function $U(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function eW(e,t){if(!(t<60))return e*3600/t}function tW(e,t,n,r){let i=r-t;if(i<50||i>QU)return;let a=n-e;if(!(a<=0))return a*1e3/i}function nW(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=tW(t.input,t.atMs,n.input,n.atMs),i=tW(t.output,t.atMs,n.output,n.atMs),a=tW(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function rW(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>QU)continue;let o=tW(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function iW(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function aW(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>iW(C.hostname())),i=n(`user`,()=>C.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function oW(e,t){let n=[],r=t=>pb(t,e.helpers).keys(),i=Ky(e,t);for(let e of Hh){let t=i[e];if(Uh(t))for(let e of r(t))n.push(e)}for(let i of Cg(Gy(e,t).node)){if(i.when)for(let e of r(i.when))n.push(e);i.kind===`segment`&&n.push(...sW(e,i.name))}return lW(e,n)}function sW(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(t=>t?[...pb(t,e.helpers).keys()]:[]):[]}function cW(e,t,n){return lW(e,[...sW(e,t),...n.flatMap(t=>[...pb(t,e.helpers).keys()])])}function lW(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[...t],i=new Set,a=t=>pb(t,e.helpers).keys(),o=new Set;for(;r.length>0;){let e=r.pop();for(let t of dW(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function uW(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=oW(e,n);return t.set(n,i),i}}function dW(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function fW(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function pW(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(XU).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function mW(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>fW(i,e),u=wO(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>L(`${e}: ${String(t)}`)):Promise.resolve(I),[p,m,h,g,_,v,y,b,ee,x,S]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,pW(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(I):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>WU(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(OU({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(Sa(xa(o.claudeConfigDir)))))]),te=[],ne=e=>{if(e.kind===`failed`){te.push(e.reason);return}return e.kind===`ok`?e.value:void 0},C=SW(p,u);te.push(...C.failures);let re=aW(o);te.push(...re.failures);let ie=ne(m),ae=ne(h),w=ne(g),T=ne(_),oe=ne(v),E=ne(y),se=ne(b),ce=_W(x);x.kind===`failed`&&te.push(`memento: ${x.reason}`);let le=hW(S,w?.maxTokens);S.kind===`failed`&&te.push(`autocompact: ${S.reason}`);for(let e of te)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?$U(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?$U(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?eW(me,he):void 0,_e=ne(ee),ve=_e===void 0?void 0:nW(_e),ye=_e===void 0?void 0:rW(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=xW(process.env.HOME??process.env.USERPROFILE),Se=e.workspace?{...e.workspace,current_dir:xW(e.workspace.current_dir)??``,project_dir:xW(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>xW(e)??e)}:e.workspace,Ce=ie===void 0?void 0:bW({cost:ie.session.cost,tokens:ie.session.tokens}),we=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},Te=T===void 0?void 0:bW({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ee=oe===void 0?void 0:vW(oe);return{...e,...Se!==void 0&&{workspace:Se},...xe!==void 0&&{home:xe},...C.git!==void 0&&{git:C.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...YU(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},feeds:n.feeds(e.session_id),...c,...s!==null&&{configPath:s},resumeCommand:qU(Se,e.session_id,o.claudeConfigDir),...Ce!==void 0&&{session:Ce},...we!==void 0&&{today:we},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...Te!==void 0&&{metrics:Te},...Ee!==void 0&&{activity:Ee},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function hW(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return sN(e.value,t)}}const gW=e=>e.trim().split(`
|
|
202
|
+
`).at(-1).trim();function _W(e){switch(e.kind){case`absent`:return;case`failed`:return{error:gW(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function vW(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=yW(e.running),i=yW(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function yW(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function bW(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function xW(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function SW(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=n.upstream===void 0?void 0:i(`tracking`,jD(n.upstream,n.aheadBehind)),p=i(`repoName`,n.repoName),m=i(`repoUrl`,n.repoUrl),h=n.pullRequest===void 0?void 0:MD(n.pullRequest,n.head),g={};switch(h?.kind){case`ok`:g={prNumber:h.value.number,prState:h.value.state,prUrl:h.value.url};break;case`failed`:r.push(`git.pr: ${h.reason}`),g={prError:h.reason};break;case`earlier`:g={prEarlier:h.value.state};break;case`absent`:case void 0:break}return{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{tracking:f},...p!==void 0&&{repoName:p},...m!==void 0&&{repoUrl:m},...g},failures:r}}function CW(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const wW={kind:`hidden`},TW={kind:`shown`};function EW(e,t){try{return CW(e,t)?TW:wW}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function DW(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function OW(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function kW({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function AW({text:e,placement:t,lead:n,trail:r}){return{text:jW(e),placement:t,...n!==void 0&&{lead:jW(n)},...r!==void 0&&{trail:jW(r)}}}function jW(e){let t=e.blankCopy(e.plain);t.style=Nv(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Nv(i).clearMetaAndLinks(),n,r);return t}function MW(e){let t=kW(e);if(t.length===1)return e.text;let n=DW(t);return n.style=e.text.style,n}function NW(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=DW(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:DW([d,...c],a)},...l.length>0&&{trail:DW([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(OW(u,n,p),[{text:u,...f}])}const PW=RegExp(`\\x1b\\[[0-9;]*m|${ad.source}`,`g`);function FW(e){return Math.max(0,...e.split(`
|
|
203
|
+
`).map(e=>Zo(e.replace(PW,``))))}function IW(e,t){let n=()=>e.map(e=>({owner:MW(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=ry(e.map(MW),t).split(`
|
|
204
|
+
`);if(i.length>1)return n();let a=Math.max(0,t.width-FW(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];OW(c,c.cellLength+a,n)}),n()}function LW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=RW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Nv(a.style)};if(e.style.link){i();let r=RW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function RW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>zW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function zW(e,t){let n=e.copy();return n.style=t,n}function BW(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function VW(e,t){let{look:n}=BW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function HW(e,t){let{layout:n}=BW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function UW(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function WW(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,GW(e,t,o,n,r,i));return i}function GW(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Qy(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=vv.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Qy(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Qy(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:JW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:JW(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:WL(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:JW(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function KW(e){return e.kind===`do`?KW(e.head):e}function qW(e){switch(KW(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function JW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function YW(e,t){return e.has(t)?Ab(e.read(t)):``}function XW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function ZW(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function QW(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Nv(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Nv(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function $W(e,t){return Math.max(e.members.indexOf(YW(t,e.stateVar)),0)}function eG(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[($W(e,r)+1)%e.members.length];return{effects:[{verb:mr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:hr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:gr,args:[XW(e.text,wD(r))]}],active:!1};case`open`:return{effects:[{verb:_r,args:[XW(e.target,wD(r))]}],active:!1};case`persist-literal`:{let t=YW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[($W(e,r)+1)%e.members.length];return{effects:[{verb:xr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Sr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Dr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`back`:return{effects:[{verb:jr,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:Mr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Tr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Er,args:[i,XW(e.name,wD(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Pr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ir,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Rr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:zr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Or,args:[i,e.key,DF(e.op)]}],active:!1};case`do`:{let a=eG(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>eG(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Or,args:[i,e.key,DF(r)]}],active:!1}}}}function tG(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,$W(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function nG(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=BW(n,`action "${e}"`).store,{display:a,boundValue:o}=tG(e,KW(r),t,i),s=YW(i,`session.id`),{effects:c,active:l}=eG(r,a.plain,o,i,s);return QW(a,Hr(c),l)}function rG(e){return{action:{fn:(t,...n)=>nG(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function iG(e,t){return ZW(`✕`,Hr([{verb:mr,args:[YW(e,`session.id`),t,P]}]),!1)}function aG(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(th(e,t,n))})}function oG({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function sG(e,t,n){return new H({color:B.fromRgba(Uc(Gm(e,`warning`),t,eh,n))})}function cG(e,t,n){return H.combine([aG(e,t,n),sG(e,t,n)])}function lG(e,t,n){return aG(e.palette,Oh(e.palette,e.disclosure,t,n),n)}function uG(e){let t=B.fromRgba(Gm(e,`background`)),n=G.fromFragments(ym.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Gm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const dG=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},fG=e=>new H({bold:e});function pG(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>dG(a,H.combine([lG(e,{...n,distribution:t},i),fG(o)]));let o=aG(e.palette,a,i);return(e,t,i,a)=>mG(i,H.combine([o,fG(a)]),r(t,n))}const mG=(e,t,n)=>dG(G.fromFragments([dG(e,t),dG(` `,t),uG(n)]));function hG(e,t){return t===void 0?(e,t,n)=>dG(n):(n,r,i)=>mG(i,void 0,t(r,e))}function gG(e,t,n,r,i){let a=aG(e.palette,i,r);return(e,r,i,o)=>dG(G.fromFragments([dG(o?`[`:` `,a),uG(n(r,t)),dG(o?`]`:` `,a)]))}function _G(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>vG(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function vG(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function yG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function bG(e){return{current:null,drawnAt:e}}function xG(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function SG(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function CG(e){return new G(e).cellLength}function wG(e){let{width:t,chromeCols:n,padding:r}=BW(e,`a row fit`);return Math.max(1,t-n-2*r)}function TG(e){let{padding:t,seamCols:n}=BW(e,`a row fit`);return Math.max(1,wG(e)-(CG(`✕`)+2*t+n))}function EG(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function DG(e,t,n){let r=CG(`←`)+1+CG(`→`)+1,i=EG(e,t,n);return(i.length>1?EG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function OG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function kG(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function AG(e,t,n){let r=e.compiled.get(t),i=r&&KW(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function jG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=BW(a,`picker`).store,d=YW(u,`session.id`),f=`stateVar`in t?YW(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?TG(a):wG(a):1/0,h=(r.kind===`led`?0:CG(`✕`)+1)+c.reduce((e,t)=>e+CG(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?DG(_.map(e=>e.cellLength),m,h):_G(g.entries,g.groups,i),y=parseInt(YW(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>Hr([{verb:mr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:mr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Hr([...eG(l,e,e,u,d).effects,...C]),ie=(e,n)=>QW(e,re(t.options[n])),ae=r.kind===`led`?[]:[ZW(`✕`,Hr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>ZW(e,Hr([...eG(l,r,r,u,d).effects,{verb:mr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(ZW(`←`,te(x-1),!1));let w=x<v.length-1?[ZW(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[OG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[OG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(OG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>CG(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:wv(a),s=` `.repeat(n-CG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(OG([ie(p(r,yG(c,m)),r)],i))}}return se}function MG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{vD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=kG(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=AG(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=SG(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=jG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,pG(u,Pm(void 0),VW(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),sG(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function NG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function PG(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function FG(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=BW(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=YW(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return OG([],!0);let d=YW(o,t.stateVar),f=NG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Hr(eG(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=QW(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):QW(hG(VW(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Hr(eG(n.compiled.get(a),p(0),void 0,o,c).effects)),b=PG(e=>v(e).cellLength,u,CG(`◀`)+1+y.cellLength+1+CG(`▶`),TG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return OG([...ee(-1).reverse(),ZW(`◀`,h(-1),!1),y,ZW(`▶`,h(1),!1),...ee(1)],!0)}function IG(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(vD(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&qW(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=AG(e,n,`carousel`),l=SG(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return FG(n,c,e,pG(l,Pm(void 0),VW(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function LG(e,t,n){let r=AG(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function RG(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function zG(e,t,n,r){let i=LG(e,t,n),a=r??YW(BW(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,VW(e,`{{ ${n} }}`))}function BG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(vD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return uG(zG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=LG(e,r,`swatches`),o=kG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=SG(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=jG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,gG(s,VW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),sG(s.palette,s.bg,c),u===0?[]:(()=>{let t=NG(l,YW(BW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[RG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const VG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function HG(e,t,n,r){let i=hh(e,n,r),a=(t,n)=>({text:t,colour:n,ink:th(e,n,r)});return[[km(t).map((n,i)=>{let a=Km(e,n);return{text:VG[i%VG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Gm(e,`warning`)),a(`error`,Gm(e,`error`))]]]}function UG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:oG({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function WG(e,t,n,r,i){let a=HG(e,t,n,r).map(e=>UG(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
205
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function GG(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(vD(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=VW(e,`{{ themePreview }}`);return WG(r===void 0?a:zG(e,r,`themePreview`),o,{...SG(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),TG(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const KG=e=>e.slice(e.lastIndexOf(`.`)+1),qG=(e,t)=>{let n=new G(KG(e));return n.truncate(t,{marker:`…`}),n.plain};function JG(e,t){let n=e.map(e=>e.map(({name:e})=>CG(KG(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function YG(e,t,n,r){let i=JG(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${qG(s,i)} `,{style:oG(Mh(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
206
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function XG(e,t){return{layoutPreview:{fn:()=>YG(HW(e,`{{ layoutPreview }}`),VW(e,`{{ layoutPreview }}`).decor,t.drawnAt(),TG(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function ZG(e,t,n,r){let i=SG(r.activeSegment,`{{ menu }}`),a=r.action,o=dk(i.placementId,e,n.key),s=mk(o),c=uk(e),l=BW(a,`menu`).store,u=YW(l,o)===c,d=YW(l,`session.id`),f=u?P:c,p=ZW(Xr(`{{ menu "${e}" }}`,t,2,+!!u),Hr([{verb:mr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=hh(i.palette,i.disclosure,t).plane,l=AG(a,e,`menu`);return jG(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,P],[s,`0`]],onPick:n.closeOnPick},n.paged,a,pG(i,n.distribution,VW(a,`{{ menu }}`),l.paletteOf,t,c),sG(i.palette,c,t))})():[]),p}const QG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $G(e,t){let n=t[t.length-1],r=QG(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:vk(r??{})}}function eK(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=$G(t,n);return ZG(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function tK(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=nK(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function nK(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function rK(e){let t={fn:(()=>{let t=SG(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>SG(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=SG(e,`{{ keptOn }}`),i=Pc(r,t),a=Pc(r,n),o=Ts(Gc(i,z.TRUECOLOR),Gc(a,z.TRUECOLOR)),s=Math.min(eh,Math.max(o,3));return(Wc(i,e.drawnAt(),(e,t)=>Ts(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=nD(()=>SG(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...iK(s)];return tK({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function iK(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function aK(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
207
207
|
`)){n.push(r);continue}let e=r.split(`
|
|
208
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function $G(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function eK(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function tK(e){return{...e,cells:e.cells.map(CW)}}function nK(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...rK(e,r)]}function rK(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function iK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:nK(e.direction,e.children.map((t,i)=>n(t,[...r,aK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function aK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:fg[e.direction]}}const oK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Nm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,vg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),nK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,aK(e,r))))}},sK={drop:e=>e.place,above:()=>`above`},cK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},lK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:pg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,yg(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,uK(e,t))};function uK(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=bD(t.scope,e.settings);if(t.gate.kind===`failed`)return dK(e,a,t,t.gate.message);try{if(!gW(i.when,a))return[];let n=hy(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:CA(n)},s=e.opens!==void 0&&gW(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:sK[g.placement](e)})),v=QG(AW(l,m)).map((e,t)=>({cells:EW(e,{...h,lead:t===0?AW(u,m):[],trail:t===0?AW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:EW(AW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>EW(AW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?cK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(SW(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],C=_.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...S,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(ne)].flatMap(SW)),[...re,...C]}catch(n){return dK(e,a,t,n.message??String(n))}}function dK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:EW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:CA(n.palette)},lead:fK(e.lead,e,t,n),trail:fK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function fK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const pK={container:oK,segment:lK};function mK(e){return pK[e]}function hK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:bO(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function gK(e,t){switch(Sg(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function _K(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:hK(n.cache),parse:gK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:hK(n.cache),parse:gK(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function vK(e,t){let n=rx.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function yK(e,t,n){let{compiled:r,loadWarnings:i}=xK(e,t,n.cwd,bK);return{...r,loadWarnings:i}}const bK=(e,t)=>TK(t);function xK(e,t,n,r){let i=SK(e),a=CK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:wK(e,t,n)}}function SK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of pv)n in t&&r.set(e,n);for(let[t,n]of Og(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function CK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function wK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{_K(t,i,a,n)}catch(e){r.push(`Variable "${i}": ${e.message??String(e)}`)}for(let[i,a]of Object.entries(e.segments))if(a.vars)for(let[e,o]of Object.entries(a.vars))try{_K(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function TK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>NW(n,`now`).registry.now(),i=()=>NW(n,`drawnAt`).registry.drawnAt(),a=pG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Iy(e.presets),l=nF(e),u=_D({extraFuncs:{...XW(n),...TG(n,a),...kG(n,a),...RG(n,a),...NG(n,a,r),...UG(n,a),...qG(o),...XG(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=vK(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map(t);n.compiled=LW(f,e.actions,h,l);let g=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};g[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let _=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},v=t=>{let r=Mg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Rg(t,e,a,t=>String(NW(n,`setting ${e}`).store.read(t.variable)))});return Object.freeze(i)},y=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:_(e.when,t,`when`),parse:(e,n)=>_(e,t,n),compileChild:y,placementSettings:v};return mK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=zy(e,t);b.set(t,y(n,r))}let ee=new Map(Ih.map(e=>[e,new Map])),x=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of x)for(let n of Ih){let r=t[n];if(!Lh(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:EK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function EK(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function DK(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function OK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Kh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Gh[e]}}function kK(e,t){return e.kind===`decided`?e.name:Gh[t]}function AK(e){return jK(e).filter(e=>!e.name.startsWith($O)).map(e=>e.id)}function jK(e){return e.kind===`container`?e.children.flatMap(jK):[e,...e.opens===void 0?[]:jK(e.opens.body)]}function MK(...e){return NK(...e).text}function NK(e,t,n,r,i,a,o,s,c=HB(e,()=>null,()=>!1)){try{var l=na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set;r.renderAt(a),r.drawAt(ng(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Gv(o),padding:o.padding,seamCols:Kv(o),look:void 0,layout:void 0};l.u(IW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Dm[c.variation],shade:Tm[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(kK(_,`palette`),kK(v,`style`),kK(y,`effect`)));let S=vD(n),te=zh(_,e=>{let n=DK(t,`palette`,e);return by(OK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=zh(v,n=>Hh(OK(`style`,DK(t,`style`,n),S,p),e.styles)),C=zh(y,e=>Xh(OK(`effect`,DK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=_y(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Lv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:eK,hold:tK});u?.clear();let w=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},T=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Eh(i,a,c),f=mG(t.activeSegment,e.name,e.id,i,d,l,u),p=TA(f,c,o.bg,o.fg,n),h=()=>ph(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)m.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:p,get trigger(){return QW(i,h().state,c)},get band(){return QW(i,h().plane,c)},get close(){return tG(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},oe=(e,t,r)=>{let i=t?yW(e.when,S):_W,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${AK(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:S,palette:ie,gate:a,padding:o.padding,region:r,perSegmentSink:u,onSegmentError:d,evaluateSegment:T,lookupSegment:w,renderChild:(e,t,n)=>oe(e,t,wh(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,Th(n)),closeDisclosure:e=>ZW(n,e),placed:ae.placed};return mK(e.kind).render(e,s)},E=t.roots.get(g);if(E===void 0)throw Error(`Preset "${g}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Py}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=yW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(pF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return gW(t.segments[e.name].when,bD(S,e.settings))}catch{return!0}};h.layout=()=>iK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=pF(e);return r===void 0?[]:[{name:r,address:t,palette:hy(n.theme,ie)}]}));let ce=$G(oe(E,!0,Ch(ee))).map(({line:e,row:t})=>{let n=kW(e.cells,o);return Xv(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||jK(E).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:ce.map(e=>e.text).join(`
|
|
209
|
-
`),motion:le}}catch(e){l.e=e}finally{l.d()}}function*
|
|
210
|
-
`)||null}function $K(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=dB(t.layers,PB,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??PB,l=a.find(e=>e.path===t.home)?.raw??{},u=new GK,d=new VO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=xK(o,d,e,r.compile??bK),n.push(...f.loadWarnings),wV(o),IF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:rW(o),lastRenderCellsBySegment:new Map,authoredRoots:XK(c,l),fileHeldSettings:uV(l),unused:[...new Map(a.flatMap(e=>LK(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function eq(e,t,n,r){let i=Qz(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[rB(e,t),tB(i)],s,c=null;try{s=$K(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Hg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:QK(o),state:null,error:e instanceof Hg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:QK(o),state:s,error:null}}function tq(e,t,n){return $K(e,{layers:[],home:``,projectDir:t},[],n)}var nq=class{entries=new Map;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??TK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=YK(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=eq(e,t,n,this.deps);a.state!==null&&this.log(`info`,qK(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??tq(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++;let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&(r.watcher?.release(),this.entries.delete(n),this.retire(r.state,`evict`))}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,JK(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=eq(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,qK(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=ZK(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const rq=16384;var iq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<rq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%rq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,expired:0,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function aq(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const oq={load:()=>({}),save:()=>{},flush:()=>{}};var sq=class{sessions;storage;head=0;atom=(0,xb.createAtom)(`SessionState`);constructor(e=oq,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,xb.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,xb.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,xb.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function cq(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var lq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return cq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const uq=new Set([`1`,`true`]),dq=new Set([`0`,`false`,``]);function fq(e,t){let n=Lq(e),r=n.scope===`segment-palette`?`string`:iv(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(uq.has(t))return`true`;if(dq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function pq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function mq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function hq(e){return/^\s*$/.test(e)?null:_i(e)}function gq(e,t){return e!==null&&yi(e,t)!==void 0}function _q(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(_q),...i}}return e}function vq(e){if(!Ey(e))return _q(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,_q(t)])),...n}}const yq=MB,bq=yq.segments,xq=yq.presets,Sq=yq.root;function Cq(e,t,n,r){if(!gq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function wq(e,t){let n=eA(t);return t.scope===`segment-palette`&&Cq(e,[`segments`,t.segment],bq[t.segment],n.join(`.`)),n}function Tq(e){return _i(Di(e))}function Eq(){return Object.entries(Sq.rows).map(([e,t])=>{let n=_q(t);return{path:[`root`],fragment:Tq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Dq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Oq(e,t){if(t===void 0)return null;let n=vq(t);return{path:e,fragment:Tq(n),unit:{path:e,value:n}}}function kq(e,t){let n=[`presets`,t],r=[...n,`root`],i=xq[t];Cq(e,n,i,r.join(`.`));let a=Dq(e,r)??Oq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Aq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function jq(e,t){return[...Eq(),Dq(e,[`root`]),kq(e,t)].filter(e=>e!==null).reduce(Aq,new Map)}function Mq(e,t,n){for(let{node:r,...i}of jq(e,t).values())if(Xi(r,n))return i;throw new J(`${Nq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Nq(e,t){return kq(e,t)?.path??[`root`]}function Pq(e,t){return t.scope===`preset-root`?Nq(e,t.preset):eA(t)}function Fq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Iq(e){let t=$k(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Lq(e){let t=Iq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Rq(e,t,n,r,i){i(t,n,Yq(t,r)),mq(t.path,r,e.logger),e.record(t.path,n,r)}function zq(e,t,n){let r=Hq(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const Bq=()=>{};function Vq(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function Hq(e,t,n){let r=Uq(e,t);if(r===null)return[];let i=new Set(qq(Kq(r),Kq(n)));return qq(Gq(e,r),Gq(e,n)).filter(e=>!i.has(e))}function Uq(e,t){try{return Wq(e,t)}catch(e){if(e instanceof Hg)return null;throw e}}function Wq(e,t){return dB(t===null?e.above:[e.path,...e.above],PB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Gq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Kq(e){return e.layers.at(-1)?.config??e.base}function qq(e,t,n=``){return!Jq(e)||!Jq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>qq(e[r],t[r],n===``?r:`${n}.${r}`))}function Jq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yq(e,t){try{return Wq(e,t)}catch(e){throw e instanceof Hg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function Xq(e,t){let n=Lq(t),r=hq(pq(e)??``),i=r===null?void 0:yi(r,eA(n));return i!==void 0&&`value`in i?i.value:void 0}function Zq(e,t,n){Qq(e,t,n,[])}function Qq(e,t,n,r){let i=pq(t.path),a=n.reduce((e,[t,n])=>Vi(e,wq(hq(e),Lq(t)),fq(t,n),Ti),i??``);Rq(e,t,i,Vq(t,()=>$q(a,t.path,r,e=>e)),zq)}function $q(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Mq(hq(s),n,i),l=ea(Fq(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function eJ(e,t,n){let r=hq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of jq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(kq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function tJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!IB(t[1])?2:0)}function nJ(e,t,n){let r=n.map(Iq),i=pq(t.path);if(i===null)return;let a=r.reduce((e,t)=>tJ(e,Pq(hq(e),t)),i);a!==i&&Rq(e,t,i,a,Bq)}function rJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function iJ(e,t){let n=new Set([...FB,...rJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(XO));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(XO(e)))}function aJ(e,t,n,r,i,a){let o=pq(t.path),s=hq(o??``),c=iJ(s,t),l=[`presets`,c],u=Vq(t,()=>kq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=Qk(c,e);return[wq(s,Lq(n)),fq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Rq(e,t,o,Vq(t,()=>$q(p,t.path,a.map(e=>({...e,preset:c})),eJ)),zq),c}function oJ(e,t,n,r){let i=pq(t.path);Rq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),zq)}function sJ(e,t,n){if(IB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=pq(t.path),a=hq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);Rq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>tJ(e,t),i),Bq)}function cJ(e,t,n,r){let i=Iq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=pq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Vq(t,()=>Mq(hq(a??``),i.preset,o)),c=Fq(a??``,s),{after:l,placed:u}=lJ(c,s.path,r,()=>{let e=Yq(t,c).config;return Iy(e.presets).map(t=>zy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Rq(e,t,a,l,zq),u}function lJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=CF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const uJ={load:()=>({}),save:()=>{}},dJ=new Set(lv.map(e=>e.sessionKey)),fJ=e=>dJ.has(e)||e.startsWith(dA),pJ=8*1024*1024,mJ={past:[],future:[]},hJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var gJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=uJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??mJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??mJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(hJ(n));r.set(hJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:aq(this.sessionState,e=>fJ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:wJ(i,n),o=r.get(e),s=o===void 0?a:OJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,EJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(hJ)),a=n.net.filter(e=>!i.has(hJ(e))),o=yJ(kJ(DJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(jJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=yJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...xJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(hJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:kJ(n,t),future:kJ(i,t),...a!==void 0&&{savepoint:{at:kJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(hJ(e))),below:kJ(a.below,t)}}}),new J(`${r}: ${o.map(jJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):pq(t.file)}write(e,t,n){t.kind===`file`?mq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||_J(n)>pJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,vJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${pJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function _J(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function vJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...xJ(n,1,[])}:{past:e,future:t.slice(1),...xJ(n,0,[])}}function yJ(e){return e.slice(-50)}const bJ=e=>e===pA.member;function xJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:SJ(e.net,n),below:e.below}}}function SJ(e,t){let n=new Map(e.map(e=>[hJ(e),e]));for(let e of t){let t=n.get(hJ(e));n.set(hJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const CJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function wJ(e,t){let n=[...e.past,t],r=yJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...xJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...TJ(e.future,a),...i.below]},n.length-r.length,t)}}function TJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function EJ(e,t){return{past:e.past.slice(0,-1),future:yJ([...e.future,t]),...xJ(e.savepoint,0,CJ(t))}}function DJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...TJ(r,t.at-i.length),...t.below]}function OJ(e,t){if(bJ(t.after)&&!bJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!bJ(t.after)&&bJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function kJ(e,t){return e.map(e=>e.filter(e=>!t.has(hJ(e)))).filter(e=>e.length>0)}function AJ(e){return e.map(jJ).join(`, `)}function jJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function MJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function NJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(MJ))}function PJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(MJ)&&NJ(t.below)}function FJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return NJ(t.past)&&NJ(t.future)&&(t.savepoint===void 0||PJ(t.savepoint))}function IJ(e,t){let n=e=>e.kind===`file`||fJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function LJ(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(FJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,IJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const RJ=e=>!fJ(e)&&!UM(e)&&e!==`update.dismissed`;var zJ=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:aq(e,RJ,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,xb.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const BJ=`click.error`;function VJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,BJ,JSON.stringify(i))}function HJ(e,t,n){let r=UJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,BJ,JSON.stringify({...r,answered:!0}))}function UJ(e,t){let n=e.get(t,BJ);return n===null?null:GJ(n)}function WJ(e,t,n,r){let i=UJ(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function GJ(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function KJ(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const qJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function JJ(e){let t=e=>({kind:`failed`,reason:e});if(!qJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!qJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Dj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Dj.join(` or `)}`)}return{kind:`ok`,value:e}}function YJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const XJ=e=>KJ(e,`doctor-marks.json`,{},JJ),ZJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},QJ=(e,t)=>e.includes(t)?e:[...e,t],$J=e=>KJ(e,`doctor-clicked-terminals.json`,[],ZJ);var eY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const tY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},nY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),rY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=nY(e,t);return r===void 0?n:r.projectDir},iY=(e,t)=>nY(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function aY(e){let t=new Map;for(let n of e.split(`
|
|
211
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*
|
|
208
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function oK(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function sK(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function cK(e){return{...e,cells:e.cells.map(AW)}}function lK(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...uK(e,r)]}function uK(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function dK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:lK(e.direction,e.children.map((t,i)=>n(t,[...r,fK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function fK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:vg[e.direction]}}const pK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Pm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,wg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),lK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,fK(e,r))))}},mK={drop:e=>e.place,above:()=>`above`},hK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},gK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:yg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Tg(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,_K(e,t))};function _K(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=ED(t.scope,e.settings);if(t.gate.kind===`failed`)return vK(e,a,t,t.gate.message);try{if(!CW(i.when,a))return[];let n=xy(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:kA(n)},s=e.opens!==void 0&&CW(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:mK[g.placement](e)})),v=aK(LW(l,m)).map((e,t)=>({cells:NW(e,{...h,lead:t===0?LW(u,m):[],trail:t===0?LW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:NW(LW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>NW(LW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?hK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(kW(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],C=_.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...S,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(ne)].flatMap(kW)),[...re,...C]}catch(n){return vK(e,a,t,n.message??String(n))}}function vK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:NW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:kA(n.palette)},lead:yK(e.lead,e,t,n),trail:yK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function yK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const bK={container:pK,segment:gK};function xK(e){return bK[e]}function SK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:EO(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function CK(e,t){switch(Og(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function wK(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:SK(n.cache),parse:CK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:SK(n.cache),parse:CK(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function TK(e,t){let n=lx.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function EK(e,t,n){let{compiled:r,loadWarnings:i}=OK(e,t,n.cwd,DK);return{...r,loadWarnings:i}}const DK=(e,t)=>MK(t);function OK(e,t,n,r){let i=kK(e),a=AK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:jK(e,t,n)}}function kK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of yv)n in t&&r.set(e,n);for(let[t,n]of Pg(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function AK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function jK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{wK(t,i,a,n)}catch(e){r.push(`Variable "${i}": ${e.message??String(e)}`)}for(let[i,a]of Object.entries(e.segments))if(a.vars)for(let[e,o]of Object.entries(a.vars))try{wK(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function MK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>BW(n,`now`).registry.now(),i=()=>BW(n,`drawnAt`).registry.drawnAt(),a=bG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Hy(e.presets),l=cF(e),u=CD({extraFuncs:{...rG(n),...MG(n,a),...IG(n,a),...GG(n,a),...BG(n,a,r),...XG(n,a),...eK(o),...rK(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=TK(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map(t);n.compiled=WW(f,e.actions,h,l);let g=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};g[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let _=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},v=t=>{let r=Rg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Wg(t,e,a,t=>String(BW(n,`setting ${e}`).store.read(t.variable)))});return Object.freeze(i)},y=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:_(e.when,t,`when`),parse:(e,n)=>_(e,t,n),compileChild:y,placementSettings:v};return xK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=Gy(e,t);b.set(t,y(n,r))}let ee=new Map(Hh.map(e=>[e,new Map])),x=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of x)for(let n of Hh){let r=t[n];if(!Uh(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:NK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function NK(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function PK(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function FK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Qh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Zh[e]}}function IK(e,t){return e.kind===`decided`?e.name:Zh[t]}function LK(e){return RK(e).filter(e=>!e.name.startsWith(ak)).map(e=>e.id)}function RK(e){return e.kind===`container`?e.children.flatMap(RK):[e,...e.opens===void 0?[]:RK(e.opens.body)]}function zK(...e){return BK(...e).text}function BK(e,t,n,r,i,a,o,s,c=YB(e,()=>null,()=>!1)){try{var l=na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set;r.renderAt(a),r.drawAt(cg(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Zv(o),padding:o.padding,seamCols:Qv(o),look:void 0,layout:void 0};l.u(UW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Om[c.variation],shade:Em[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(IK(_,`palette`),IK(v,`style`),IK(y,`effect`)));let S=wD(n),te=Gh(_,e=>{let n=PK(t,`palette`,e);return Ey(FK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=Gh(v,n=>Jh(FK(`style`,PK(t,`style`,n),S,p),e.styles)),C=Gh(y,e=>ng(FK(`effect`,PK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=Cy(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Uv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:sK,hold:cK});u?.clear();let w=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},T=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Mh(i,a,c),f=xG(t.activeSegment,e.name,e.id,i,d,l,u),p=jA(f,c,o.bg,o.fg,n),h=()=>hh(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)m.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:p,get trigger(){return aG(i,h().state,c)},get band(){return aG(i,h().plane,c)},get close(){return cG(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},oe=(e,t,r)=>{let i=t?EW(e.when,S):wW,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${LK(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:S,palette:ie,gate:a,padding:o.padding,region:r,perSegmentSink:u,onSegmentError:d,evaluateSegment:T,lookupSegment:w,renderChild:(e,t,n)=>oe(e,t,Ah(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,jh(n)),closeDisclosure:e=>iG(n,e),placed:ae.placed};return xK(e.kind).render(e,s)},E=t.roots.get(g);if(E===void 0)throw Error(`Preset "${g}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${By}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=EW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(yF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return CW(t.segments[e.name].when,ED(S,e.settings))}catch{return!0}};h.layout=()=>dK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=yF(e);return r===void 0?[]:[{name:r,address:t,palette:xy(n.theme,ie)}]}));let ce=oK(oe(E,!0,kh(ee))).map(({line:e,row:t})=>{let n=IW(e.cells,o);return ny(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||RK(E).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:ce.map(e=>e.text).join(`
|
|
209
|
+
`),motion:le}}catch(e){l.e=e}finally{l.d()}}function*VK(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*HK(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of Hy(e.presets)){for(let n of Cg(Gy(e,t).node))n.when!==void 0&&(yield n.when);let n=Ky(e,t);for(let e of Hh){let t=n[e];Uh(t)&&(yield t)}}for(let[,t]of VK(e))t.kind===`template`&&(yield t.template),Ag(t)&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function UK(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function WK(e,t){let n=new Set,r=new Set,i=new Set;for(let e of HK(t)){for(let r of pb(e,t.helpers).keys())n.add(r);for(let{name:n}of _b(e,t.helpers))r.add(n);for(let n of vb(e,t.helpers))i.add(n)}for(let[,e]of VK(t))if(Ag(e)&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Hy(t.presets))for(let n of Cg(Gy(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>UK(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!sk(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(VK(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var GK=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,ZK(e,t,n,`initial value`),this.cell=Db.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){ZK(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},KK=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,Db.computed)(()=>{let e=n();return ZK(this.name,this.type,e,`computed result`),e},{keepAlive:!0}),typeof this.cell.suspend_!=`function`)throw TypeError(`Variable "${e}": this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`Variable "${e}": this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}lastUpdatedMs(){return null}},qK=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Db.observable.box(XK(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=XK(e);YK(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function JK(e){return JSON.stringify(e)}function YK(e,t){return JK(e)===JK(t)}function XK(e){return e.kind===`ok`?{kind:`ok`,value:Ob(e.value)}:e}function ZK(e,t,n,r){let i=kb(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var QK=class{nodes=Db.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new GK(e,t,n))}defineDocument(e,t){this.declare(e,new qK(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new KK(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Db.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Db.runInAction)(()=>n.set(t))}runInAction(e){(0,Db.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return JK(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,Db.runInAction)(()=>{for(let t of this.nodes.values())t instanceof KK&&(t.release(),e++)}),e}disposed=!1;requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}declare(e,t){if(this.disposed)throw Error(`Variable "${e}": cannot declare on a disposed store`);if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`);(0,Db.runInAction)(()=>this.nodes.set(e,t))}};function $K(e){return Math.floor(e/4)}function eq(e,{plugins:t,config:n}){let{checkout:r,loaded:i,dropped:a,unreached:o}=t,s=r===null?`-`:`${r.git?`git`:`dir`}:${r.root}`,c=e=>{let t=Ez(e),r=t===void 0?void 0:n.variables[Oz(t)];return r?.kind===`file`?r.path:`none`};return`config load ${e.join(` < `)||`<default>`}: plugins loaded=${i.length} dropped=${a.length} unplaced=${o.length} checkout=${s}`+i.map(e=>` +${e} data=${c(e)}`).join(``)+a.map(e=>` -${e.path} (${e.reason})`).join(``)+o.map(e=>` ~${e.path} (${e.reason})`).join(``)}function tq(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function nq(e,t,n){return e+`\0`+t+`\0`+(n??``)}function rq(e,t){return new Set(Hy(e.presets).filter(n=>Gy(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function iq(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...rB(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=Cb(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Cb(s.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function aq(e){return e.filter(Boolean).join(`
|
|
210
|
+
`)||null}function oq(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vB(t.layers,VB,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??VB,l=a.find(e=>e.path===t.home)?.raw??{},u=new QK,d=new qO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=OK(o,d,e,r.compile??DK),n.push(...f.loadWarnings),jV(o),HF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:uW(o),lastRenderCellsBySegment:new Map,authoredRoots:rq(c,l),fileHeldSettings:_V(l),unused:[...new Map(a.flatMap(e=>WK(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function sq(e,t,n,r){let i=aB(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[uB(e,t),cB(i)],s,c=null;try{s=oq(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Jg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:aq(o),state:null,error:e instanceof Jg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:aq(o),state:s,error:null}}function cq(e,t,n){return oq(e,{layers:[],home:``,projectDir:t},[],n)}var lq=class{entries=new Map;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??MK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=nq(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=sq(e,t,n,this.deps);a.state!==null&&this.log(`info`,eq(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??cq(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++;let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&(r.watcher?.release(),this.entries.delete(n),this.retire(r.state,`evict`))}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,tq(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=sq(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,eq(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=iq(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const uq=16384;var dq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<uq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%uq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,expired:0,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function fq(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const pq={load:()=>({}),save:()=>{},flush:()=>{}};var mq=class{sessions;storage;head=0;atom=(0,Db.createAtom)(`SessionState`);constructor(e=pq,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Db.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Db.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Db.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function hq(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var gq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return hq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const _q=new Set([`1`,`true`]),vq=new Set([`0`,`false`,``]);function yq(e,t){let n=Wq(e),r=n.scope===`segment-palette`?`string`:uv(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(_q.has(t))return`true`;if(vq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function bq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function xq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Sq(e){return/^\s*$/.test(e)?null:_i(e)}function Cq(e,t){return e!==null&&yi(e,t)!==void 0}function wq(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(wq),...i}}return e}function Tq(e){if(!My(e))return wq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,wq(t)])),...n}}const Eq=zB,Dq=Eq.segments,Oq=Eq.presets,kq=Eq.root;function Aq(e,t,n,r){if(!Cq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function jq(e,t){let n=oA(t);return t.scope===`segment-palette`&&Aq(e,[`segments`,t.segment],Dq[t.segment],n.join(`.`)),n}function Mq(e){return _i(Di(e))}function Nq(){return Object.entries(kq.rows).map(([e,t])=>{let n=wq(t);return{path:[`root`],fragment:Mq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Pq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Fq(e,t){if(t===void 0)return null;let n=Tq(t);return{path:e,fragment:Mq(n),unit:{path:e,value:n}}}function Iq(e,t){let n=[`presets`,t],r=[...n,`root`],i=Oq[t];Aq(e,n,i,r.join(`.`));let a=Pq(e,r)??Fq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Lq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function Rq(e,t){return[...Nq(),Pq(e,[`root`]),Iq(e,t)].filter(e=>e!==null).reduce(Lq,new Map)}function zq(e,t,n){for(let{node:r,...i}of Rq(e,t).values())if(Xi(r,n))return i;throw new J(`${Bq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Bq(e,t){return Iq(e,t)?.path??[`root`]}function Vq(e,t){return t.scope===`preset-root`?Bq(e,t.preset):oA(t)}function Hq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Uq(e){let t=aA(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Wq(e){let t=Uq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Gq(e,t,n,r,i){i(t,n,nJ(t,r)),xq(t.path,r,e.logger),e.record(t.path,n,r)}function Kq(e,t,n){let r=Yq(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const qq=()=>{};function Jq(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function Yq(e,t,n){let r=Xq(e,t);if(r===null)return[];let i=new Set(eJ($q(r),$q(n)));return eJ(Qq(e,r),Qq(e,n)).filter(e=>!i.has(e))}function Xq(e,t){try{return Zq(e,t)}catch(e){if(e instanceof Jg)return null;throw e}}function Zq(e,t){return vB(t===null?e.above:[e.path,...e.above],VB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Qq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function $q(e){return e.layers.at(-1)?.config??e.base}function eJ(e,t,n=``){return!tJ(e)||!tJ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>eJ(e[r],t[r],n===``?r:`${n}.${r}`))}function tJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nJ(e,t){try{return Zq(e,t)}catch(e){throw e instanceof Jg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function rJ(e,t){let n=Wq(t),r=Sq(bq(e)??``),i=r===null?void 0:yi(r,oA(n));return i!==void 0&&`value`in i?i.value:void 0}function iJ(e,t,n){aJ(e,t,n,[])}function aJ(e,t,n,r){let i=bq(t.path),a=n.reduce((e,[t,n])=>Vi(e,jq(Sq(e),Wq(t)),yq(t,n),Ti),i??``);Gq(e,t,i,Jq(t,()=>oJ(a,t.path,r,e=>e)),Kq)}function oJ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=zq(Sq(s),n,i),l=ea(Hq(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function sJ(e,t,n){let r=Sq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of Rq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(Iq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function cJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!UB(t[1])?2:0)}function lJ(e,t,n){let r=n.map(Uq),i=bq(t.path);if(i===null)return;let a=r.reduce((e,t)=>cJ(e,Vq(Sq(e),t)),i);a!==i&&Gq(e,t,i,a,qq)}function uJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function dJ(e,t){let n=new Set([...HB,...uJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(nk));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(nk(e)))}function fJ(e,t,n,r,i,a){let o=bq(t.path),s=Sq(o??``),c=dJ(s,t),l=[`presets`,c],u=Jq(t,()=>Iq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=iA(c,e);return[jq(s,Wq(n)),yq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Gq(e,t,o,Jq(t,()=>oJ(p,t.path,a.map(e=>({...e,preset:c})),sJ)),Kq),c}function pJ(e,t,n,r){let i=bq(t.path);Gq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),Kq)}function mJ(e,t,n){if(UB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=bq(t.path),a=Sq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);Gq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>cJ(e,t),i),qq)}function hJ(e,t,n,r){let i=Uq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=bq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Jq(t,()=>zq(Sq(a??``),i.preset,o)),c=Hq(a??``,s),{after:l,placed:u}=gJ(c,s.path,r,()=>{let e=nJ(t,c).config;return Hy(e.presets).map(t=>Gy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Gq(e,t,a,l,Kq),u}function gJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=kF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const _J={load:()=>({}),save:()=>{}},vJ=new Set(hv.map(e=>e.sessionKey)),yJ=e=>vJ.has(e)||e.startsWith(_A),bJ=8*1024*1024,xJ={past:[],future:[]},SJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var CJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=_J){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??xJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??xJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(SJ(n));r.set(SJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:fq(this.sessionState,e=>yJ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:jJ(i,n),o=r.get(e),s=o===void 0?a:FJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,NJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(SJ)),a=n.net.filter(e=>!i.has(SJ(e))),o=EJ(IJ(PJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(RJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=EJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...OJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(SJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:IJ(n,t),future:IJ(i,t),...a!==void 0&&{savepoint:{at:IJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(SJ(e))),below:IJ(a.below,t)}}}),new J(`${r}: ${o.map(RJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):bq(t.file)}write(e,t,n){t.kind===`file`?xq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||wJ(n)>bJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,TJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${bJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function wJ(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function TJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...OJ(n,1,[])}:{past:e,future:t.slice(1),...OJ(n,0,[])}}function EJ(e){return e.slice(-50)}const DJ=e=>e===yA.member;function OJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:kJ(e.net,n),below:e.below}}}function kJ(e,t){let n=new Map(e.map(e=>[SJ(e),e]));for(let e of t){let t=n.get(SJ(e));n.set(SJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const AJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function jJ(e,t){let n=[...e.past,t],r=EJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...OJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...MJ(e.future,a),...i.below]},n.length-r.length,t)}}function MJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function NJ(e,t){return{past:e.past.slice(0,-1),future:EJ([...e.future,t]),...OJ(e.savepoint,0,AJ(t))}}function PJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...MJ(r,t.at-i.length),...t.below]}function FJ(e,t){if(DJ(t.after)&&!DJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!DJ(t.after)&&DJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function IJ(e,t){return e.map(e=>e.filter(e=>!t.has(SJ(e)))).filter(e=>e.length>0)}function LJ(e){return e.map(RJ).join(`, `)}function RJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function zJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function BJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(zJ))}function VJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(zJ)&&BJ(t.below)}function HJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return BJ(t.past)&&BJ(t.future)&&(t.savepoint===void 0||VJ(t.savepoint))}function UJ(e,t){let n=e=>e.kind===`file`||yJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function WJ(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(HJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,UJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const GJ=e=>!yJ(e)&&!YM(e)&&e!==`update.dismissed`;var KJ=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:fq(e,GJ,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Db.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const qJ=`click.error`;function JJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,qJ,JSON.stringify(i))}function YJ(e,t,n){let r=XJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,qJ,JSON.stringify({...r,answered:!0}))}function XJ(e,t){let n=e.get(t,qJ);return n===null?null:QJ(n)}function ZJ(e,t,n,r){let i=XJ(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function QJ(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function $J(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const eY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function tY(e){let t=e=>({kind:`failed`,reason:e});if(!eY(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!eY(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Nj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Nj.join(` or `)}`)}return{kind:`ok`,value:e}}function nY(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const rY=e=>$J(e,`doctor-marks.json`,{},tY),iY=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},aY=(e,t)=>e.includes(t)?e:[...e,t],oY=e=>$J(e,`doctor-clicked-terminals.json`,[],iY);var sY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const cY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},lY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),uY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=lY(e,t);return r===void 0?n:r.projectDir},dY=(e,t)=>lY(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function fY(e){let t=new Map;for(let n of e.split(`
|
|
211
|
+
`)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*pY(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const mY={pullRequests:e=>pW(e).showPullRequest===!0,rateLimits:e=>fW(e,`block`)||fW(e,`weekly`),memento:e=>fW(e,`memento`)};function hY(e,t){let n=new Map;for(let r of Cg(Gy(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>Ng(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,cW(e,t,n.get(t))])),a=e=>r.filter(t=>mY[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`),memento:a(`memento`)}}
|
|
212
212
|
/*!
|
|
213
213
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
214
214
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -236,9 +236,9 @@ print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
|
|
|
236
236
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
237
237
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
238
238
|
*/
|
|
239
|
-
function
|
|
239
|
+
function gY(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function _Y(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
240
240
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
241
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
241
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=gY(t.toml,t.ptr),i=_Y(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
|
|
242
242
|
/*!
|
|
243
243
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
244
244
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -266,7 +266,7 @@ function lY(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
266
266
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
267
267
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
268
268
|
*/
|
|
269
|
-
function
|
|
269
|
+
function vY(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
|
|
270
270
|
`:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
|
|
271
271
|
/*!
|
|
272
272
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -295,7 +295,7 @@ function dY(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
295
295
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
296
296
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
297
297
|
*/
|
|
298
|
-
let
|
|
298
|
+
let yY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var bY=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(yY);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
|
|
299
299
|
/*!
|
|
300
300
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
301
301
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -323,7 +323,7 @@ let fY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
323
323
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
324
324
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
325
325
|
*/
|
|
326
|
-
function
|
|
326
|
+
function xY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function SY(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function CY(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?PY(e):NY(e);return e.d++,t}return r===34||r===39?vY(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?wY(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?DY(e,r,t):e.s.charCodeAt(e.p+2)===58?OY(e,r,t):wY(e,e.p,r,0,t)}function wY(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||SY(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return TY(e,t,16,i);if(a===98)return TY(e,t,2,i);if(a===111)return TY(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else xY(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!SY(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:xY(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):EY(e,c,10,t)}function TY(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!SY(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):xY(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),EY(e,o,n,t)}function EY(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function DY(e,t,n){let r=e.p++,i;if(!xY(t)||!xY(e.s.charCodeAt(e.p++))||!xY(e.s.charCodeAt(e.p++))||!xY(e.s.charCodeAt(e.p++)))return wY(e,e.p=r,t,0,n);if(e.p+=5,xY(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!xY(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return kY(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;xY(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return kY(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return kY(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return kY(e,e.s.slice(r,e.p),2,i,r)}function OY(e,t,n){let r=e.p;if(!xY(t)||!xY(e.s.charCodeAt(++e.p)))return wY(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;xY(e.s.charCodeAt(++e.p)););return kY(e,e.s.slice(r,e.p),4,!1,r)}function kY(e,t,n,r,i,a){if(e.ld){let a=new bY(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
|
|
327
327
|
/*!
|
|
328
328
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
329
329
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -351,7 +351,7 @@ function mY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
351
351
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
352
352
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
353
353
|
*/
|
|
354
|
-
function
|
|
354
|
+
function AY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function jY(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;AY(e)}}
|
|
355
355
|
/*!
|
|
356
356
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
357
357
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -379,7 +379,7 @@ function CY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
379
379
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
380
380
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
381
381
|
*/
|
|
382
|
-
function
|
|
382
|
+
function MY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(vY(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function NY(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(jY(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=MY(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),jY(e,!0,!0);let l=CY(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),jY(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function PY(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(jY(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(CY(e,93)),jY(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
|
|
383
383
|
/*!
|
|
384
384
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
385
385
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -407,7 +407,7 @@ function TY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
407
407
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
408
408
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
409
409
|
*/
|
|
410
|
-
function
|
|
410
|
+
function FY(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function IY(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function LY(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,jY(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=MY(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=FY(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(IY(n,u,a),o=!0)}else{a=n.p;let e=FY(n,MY(n),s,c,0);!e&&!o&&IY(n,e,a),jY(n,!0,!0);let t=CY(n,void 0);e&&!o&&(e[1][e[0]]=t)}jY(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),jY(n)}return r}``.isWellFormed;
|
|
411
411
|
/*!
|
|
412
412
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
413
413
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -435,7 +435,7 @@ function OY(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
|
|
|
435
435
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
436
436
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
437
437
|
*/
|
|
438
|
-
const
|
|
438
|
+
const RY=e=>e.codePointAt(0).toString(16).toUpperCase(),zY=String.raw`
|
|
439
439
|
ObjC.import("AppKit");
|
|
440
440
|
ObjC.import("CoreText");
|
|
441
441
|
function lacksOf(font, points) {
|
|
@@ -482,49 +482,49 @@ function run(argv) {
|
|
|
482
482
|
: iterm(argv[1], points),
|
|
483
483
|
);
|
|
484
484
|
}
|
|
485
|
-
`;function
|
|
486
|
-
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const
|
|
487
|
-
`,`:family=${
|
|
488
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function
|
|
485
|
+
`;function BY(e){let t=ut({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,zY,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new sY(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const VY=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),HY=e=>[...e].map(RY).join(`,`);function UY(e,t){let n=BY([`font`,e.kind,e.name,HY(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:VY(r)}}}function WY(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!gj(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const GY=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function KY(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>WY(e,n));if(t!==null)return r[0];let i=r.find(e=>!GY(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function qY(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=BY([`iterm`,r??``,HY(n)]);return i.kind===`failed`?i:KY(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:VY(e.lacks)})),r,e)}function JY(e,t){let n=e.split(`
|
|
486
|
+
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const YY=e=>e.replace(/[\\:,=-]/g,`\\$&`);function XY(e,t){let n=ut({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
487
|
+
`,`:family=${YY(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new sY(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return JY(n.stdout,t)}function ZY(e,t){return process.platform===`darwin`?UY(e,t):XY(e.name,t)}function QY(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function $Y(e){return e===`darwin`?`Menlo`:`monospace`}const eX=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function tX(e){let t=eX(e.font)?e.font:{},n=eX(t.normal)?t.normal:{},r=(eX(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function nX(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=LY(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=tX(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=nX(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function rX(e,t){let n=C.homedir(),r=QY(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:nX(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??$Y(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=ZY({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const iX={iterm2:qY,alacritty:(e,t,n)=>rX(t,n)};function aX(e,t,n){return iX[e.name](e.version,t,n)}function oX(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const sX=e=>$J(e,`doctor-post-mortems-read.json`,{through:null},oX);function cX(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const lX={realpath:e=>cX(()=>p.realpathSync(e)),checkoutOf:Je,digest:e=>cX(()=>Ge(e)),nativeShipped:Wa(process.platform,process.arch)};function uX(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const dX=e=>({marks:rY(e),clicked:oY(e),postMortemsRead:sX(e)}),fX=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function pX(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const mX=/^(sshd|mosh-server)\b/;function hX(e,t){let n=fY(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of pY(n,t))if(mX.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function gX(e){let t=ut({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new sY(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return hX(t.stdout,e)}const _X=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function vX(e,t){let n=[];for(let r of e.split(`
|
|
488
|
+
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function yX(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=_X.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function bX(){let e=ut({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:vX(e.stdout,yX)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function xX(e){let t=SU(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new sY(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:pX(t.stdout)}function SX(e){return{probeTmux:xX,remoteLogin:gX,fontInUse:aX,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ka(process.platform),install:lX,daemons:bX,forge:DX,memento:zU,transcript:wX}}function CX(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
489
489
|
`)+1,i=n.lastIndexOf(`
|
|
490
490
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
491
|
-
`)){let t=
|
|
492
|
-
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const
|
|
493
|
-
`);let i=
|
|
491
|
+
`)){let t=VH(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function wX(e){let t=va(e,Pj+1);return t.kind===`ok`?F(CX(t.value.buf,t.value.fromStart)):t}function TX(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const EX={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function DX(e){if(kD(e)===void 0)return{kind:`ok`,value:null};let t=JD(ut({bin:`git`,args:[...qD],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=$D(t.value);if(n===null)return{kind:`ok`,value:null};let r=KD(n);if(r===null)return{kind:`ok`,value:null};let i=VD[r],a=EX[r],o=a.loginHost(GD(n)),s=ut({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return OX(i,o,a.nonZero,s)}function OX(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):HD(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:RD(r.stderr)}):{kind:`failed`,reason:LD(e,r)}}function kX(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
|
|
492
|
+
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const AX=e=>cX(()=>ja(e));function jX(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Sa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:AX(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}function MX(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function NX(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Cj(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:Sj(t),tmuxClient:t}}}}function PX(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(fj(s))return{kind:`bundling`,name:s,version:c};if(!pj(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function FX(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:qe};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function IX(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function LX(e,t,n,r,i){return{pullRequests:IX(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:IX(t.rateLimits,()=>i),memento:IX(t.memento,()=>({located:e.memento(r,n.projectDir),claudeConfigDir:r}))}}function RX(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}function zX(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=YB(d.config,r,()=>!1),p=MX(e,t.tmux),m=NX(p,t.terminalEnv),h=[...new Set([...ty(f),...ey(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:PX(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:kX(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:LX(e,hY(d.config,f.preset),n,xa(t.claudeConfigDir),a),transcripts:TX(e,o),claudeSettings:jX({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Sa(xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function BX(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;O(e,Vi(Ea(e),t.path,JSON.stringify(t.value),Ei));let r=e=>({...e,sources:AX(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||In(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const VX={connectMs:200,budgetMs:500};async function HX(e){let n=e.includes(`--json`),r=await UX();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${ln(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
493
|
+
`);let i=WX(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(QX(r.value))}function UX(){return nn({kind:`stats`},VX,e=>`stats`in e?e.stats:void 0)}function WX(e,t=GX){let n=dq.referenceSnapshot(),r=KX(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=JX(e.version,e.sourceDigest??null),a=JX(qe,Xe());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const GX=Object.keys(dq.referenceSnapshot());function KX(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!qX(e))return[];if(!qX(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...KX(e[i],t[i],a)):r.push(a)}return r}function qX(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JX(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function YX(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function XX(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function ZX(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function QX(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${JX(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${ZX(e.uptimeSec)}`),t.push(` rss ${YX(e.rssBytes)}`),t.push(` heapUsed ${YX(e.heapUsedBytes)}`),t.push(` heapTotal ${YX(e.heapTotalBytes)}`),t.push(` external ${YX(e.externalBytes)}`),t.push(` arrayBuffers ${YX(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` expired ${e.gitCache.expired}`),t.push(` hit rate ${XX(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${XX(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${YX(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${YX(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` accounted ${YX(e.renderCache.accountedBytes)} / ${YX(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
494
494
|
`)+`
|
|
495
|
-
`}const
|
|
496
|
-
`).join(` — `));let t=
|
|
497
|
-
`);return{inMode:n!==`0`,screen:r}}function _Z(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function vZ(e,t){let n=hZ(e,`claude-input.type`,_Z(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function yZ(){return{read:gZ,type:vZ}}function bZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function xZ(e){return SZ(()=>decodeURIComponent(e))}function SZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function CZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const wZ=(e,t)=>CZ(xZ(e),t),TZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,xZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},EZ=(e,t)=>CZ(xZ(e),t),DZ=(e,t)=>CZ(xZ(e),t),OZ=(e,t)=>{let n=bZ(xZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},kZ=(e,t)=>{let[n=``,...r]=SZ(()=>Vr(e)),i=bZ(n),a=wV(UZ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}NZ(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},AZ=/^-?\d+$/;function jZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const MZ=(e,t)=>{let[n=``,r=``,i=``]=SZ(()=>Vr(e)),a=bZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!AZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=UZ(t,a),c=wV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&AZ.test(u)?PZ(l,parseInt(u,10)):FZ(`step-state`,r,l,DV(s,e=>t.sessionState.get(a,e),r)),f=jZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);NZ(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function NZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(dA));if(i.length===0)return;let a=rV(UZ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function PZ(e,t){return Math.max(e.min,Math.min(e.max,t))}function FZ(e,t,n,r){if(r===null)return n.min;if(!AZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return PZ(n,parseInt(r,10))}const IZ=`render-origin`;function LZ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function RZ(e){return JSON.stringify(e)}function zZ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function BZ(e,t){let n=VZ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function VZ(e,t){let n=e.sessionState.get(t,IZ);return n===null?null:LZ(zZ(n),e.sessionState,t)}function HZ(e,t,n){let r=VZ(e,t);if(r===null)return;let{path:i}=WZ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function UZ(e,t){return e.configFor(BZ(e,t))}function WZ(e){return eB(e.projectDir,e.cwd,e.configFile??void 0)}function GZ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const KZ=(e,t)=>{let[n=``,r=``,i=``]=SZ(()=>Vr(e)),a=bZ(n),o=BZ(t,a),s=t.configFor(o),c=IF(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=WZ(o),d=tV(s,e=>t.sessionState.get(a,e),r);Zq(GZ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},qZ=(e,t)=>{let[n=``,r=``,i=``]=SZ(()=>Vr(e)),a=bZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!AZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=BZ(t,a),c=t.configFor(s),l=IF(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=WZ(s),f=tV(c,e=>t.sessionState.get(a,e),r),p=Xq(d.path,f.key),m=typeof p==`number`?PZ(u,p):FZ(`step-config`,r,u,RF(f.globals,r)),h=jZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);Zq(GZ(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},JZ=(e,t)=>{let[n=``]=SZ(()=>Vr(e)),r=bZ(n),i=BZ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=$B(a,o),c=nV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=wV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});XZ(`save`,l,c);let d=WZ(i);Qq(GZ(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(YZ)].join(` `)} → ${d.path} (session=${r})`)},YZ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Ig(e.value)}`;function XZ(e,t,n){for(let r of n){let n=t.validate(r.key,Ig(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const ZZ=(e,t)=>{let[n=``]=SZ(()=>Vr(e)),r=bZ(n),i=BZ(t,r),a=t.configFor(i),o=oV(a,e=>t.sessionState.get(r,e)),s=wV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});XZ(`save-preset`,s,o.placements);let l=WZ(i),u=aJ(GZ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...lv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,sv.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(YZ)].join(` `)} → ${l.path} (session=${r})`)},QZ=(e,t)=>{let[n=``]=SZ(()=>Vr(e)),r=bZ(n),i=BZ(t,r),a=cV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=WZ(i);oJ(GZ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set($B(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ev.map(e=>sv[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${ev.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},$Z=(e,t)=>{let[n=``,r=``]=SZ(()=>Vr(e)),i=bZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=BZ(t,i),o=WZ(a);sJ(GZ(t,i),o,r),t.reloadConfig(a);let s=sv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},eQ=(e,t)=>{let[n=``,...r]=SZ(()=>Vr(e)),i=bZ(n),a=BZ(t,i),o=IF(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=WZ(a),l=r.map(lV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);nJ(GZ(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function tQ(e,t){let n=(e,t)=>[..._g(zy(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Iy(t.presets).flatMap(e=>n(t,e).map(t=>fA(XO(e),pg(t)))));return Iy(e.presets).flatMap(t=>n(e,t).map(e=>({member:fA(XO(t),pg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function nQ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[oA]:[]])}const rQ=(e,t)=>{let[n=``,r=``,i=``]=SZ(()=>Vr(e)),a=bZ(n),o=BZ(t,a),s=t.configFor(o),c=IF(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=SF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=WZ(o),f=cJ(GZ(t,a),d,r,u);t.reloadConfig(o);let p=nQ(tQ(s,t.configFor(o)),t.sessionState.get(a,oA)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},iQ=(e,t)=>{let[n=``]=SZ(()=>Vr(e)),r=bZ(n);t.journal.commit();let i=t.history.undo(r);HZ(t,r,i),t.dlog(`info`,`undo: restored ${AJ(i)} (session=${r})`)},aQ=(e,t)=>{let n=bZ(xZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,wV(UZ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},oQ=(e,t)=>{let n=bZ(xZ(e));t.journal.commit();let r=t.history.rewind(n);HZ(t,n,r),t.dlog(`info`,`rewind: put back ${AJ(r)||`nothing`} as edit mode found it (session=${n})`)},sQ=(e,t)=>{let[n=``]=SZ(()=>Vr(e)),r=bZ(n);t.journal.commit();let i=t.history.redo(r);HZ(t,r,i),t.dlog(`info`,`redo: re-applied ${AJ(i)} (session=${r})`)},cQ=(e,t)=>{bZ(xZ(e)),t.applyUpdate()},lQ=`client-hints`;function uQ(e,t){let n=e.sessionState.get(t,lQ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function dQ(e,t,n){let r=yM(n);e.sessionState.setBatch(t,LM(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${FM(n.nerdFont,n.marks)} ${TM(n.terminal,n.clicked)} ${EM(n.terminal,n.width)} ${DM(n.install)} ${kM(n.daemon)} ${AM(n.data)} ${PM(n.transcripts)} ${jM(n.frames,n.claudeSettings)} ${NM(n.claudeSettings.origin.sources)} (session=${t})`)}function fQ(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,_O(new Date)),i;try{i=MX(e.doctor,uQ(e,t),BZ(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:iY(n,r)},jX(t,r),aX(e.doctorStores))}catch(e){throw e instanceof eY?new J(e.message):e}return{...i,urlHandler:OX(e.arrival),install:rX(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:pQ(e,i)}}function pQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?vj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>QJ(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const mQ=(e,t)=>{let n=bZ(xZ(e));dQ(t,n,fQ(t,n))},hQ=(e,t)=>{let n=XX(xZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new J(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},gQ=(e,t)=>{let[n=``,r=``]=SZ(()=>Vr(e)),i=bZ(n),a=bM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=fQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=NX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Aj(s.fix)} (session=${i})`),dQ(t,i,c.value)},_Q=(e,t)=>{let[n=``,r=``,i=``]=SZ(()=>Vr(e)),a=bZ(n),o=bM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!Dj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${Dj.join(` or `)}`);let s=fQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>YJ(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),dQ(t,a,{...s,marks:u})},vQ=(e,t)=>{let[n=``,...r]=SZ(()=>Vr(e)),i=bZ(n),a=BZ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=RL(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=xU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},uQ(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},yQ=(e,t)=>{let[n=``,r=``]=SZ(()=>Vr(e)),i=bZ(n),a=Object.values(t.configFor(BZ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=mZ(t.claudeInput,uQ(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},bQ=`config-override`,xQ=new Map([[gr,wZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=bZ(SZ(()=>decodeURIComponent(e.slice(0,n)))),i=SZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,bQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,bQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[_r,TZ],[mr,kZ],[hr,MZ],[xr,KZ],[Sr,qZ],[Dr,eQ],[Cr,JZ],[wr,ZZ],[Tr,QZ],[Er,$Z],[Or,rQ],[kr,iQ],[Ar,sQ],[jr,aQ],[Mr,oQ],[yr,EZ],[br,DZ],[vr,OZ],[Nr,cQ],[Pr,mQ],[Fr,gQ],[Ir,_Q],[Lr,hQ],[Rr,vQ],[zr,yQ]]),SQ=new Set([mr,hr,xr,Sr,Dr,Cr,wr,Tr,Er,Or,kr,Ar,jr,Mr,vr,Nr,Pr,Fr,Ir,Rr,zr]),CQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Gr(Ur(e))){if(!i&&SQ.has(a)){let e=Vr(o);e.length>0&&e[0]&&(i=e[0])}let e=xQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&VJ(t.sessionState,i,n.join(`
|
|
498
|
-
`),_O(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function wQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const TQ=new Map([...xQ,[pr,CQ]].map(([e,t])=>[e,wQ(t)]));Object.freeze([...TQ.keys()]);const EQ=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),DQ=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],OQ=[[`workspace.added_dirs`,`string-list`]];function kQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of DQ){let i=MQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=AQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of OQ){let i=MQ(n,e),a=i===void 0?r:jQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))EQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function AQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function jQ(e){return Array.isArray(e)&&e.every(e=>AQ(e)===`string`)?`string-list`:AQ(e)}function MQ(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function NQ(e,t){switch(e){case`vars`:return{what:e,vars:PQ(t)};case`segments`:return{what:e,segments:zQ(t)};case`config`:return{what:e,config:UQ(t)}}}function PQ(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=LQ(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=FQ(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:IQ(r.lastUpdatedMs())})}return o}function FQ(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function IQ(e){return e===null?null:Math.max(0,Date.now()-e)}function LQ(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,RQ(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,RQ(i));return t}function RQ(e){return e.kind}function zQ(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=VQ(n),o=BQ(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:HQ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function BQ(e){let t=new Map;for(let n of Iy(e.presets))for(let r of _g(zy(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=pg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function VQ(e){let t=[],n=new Set;for(let r of _g(ky(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function HQ(e,t,n){let r=new Set;for(let i of sb(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function UQ(e){return e===null?null:e.config}const WQ=[`vars`,`segments`,`config`];function GQ(e){return typeof e==`string`&&WQ.includes(e)}function KQ(e){return Math.max(1,e-2)}const qQ={moving:1e3/30,still:1e3},JQ=1e3;function YQ(e){return E_.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function XQ(e,t){e.push(t);let n=e.findIndex(e=>e>t-JQ);e.splice(0,n)}const ZQ=e=>({resp:e,bytes:JSON.stringify(e)}),QQ=(e,t)=>T_[t].elsewhere===null?e.statusline:e.bar,$Q=e=>Math.round(1e3/e);var e$=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return M_;let n=this.deps.now()-JQ,r=this.shown(t);return j_(e=>{let i=t.rates.get(e);if(i===void 0)return k_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:$Q(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=$Q(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:ZQ(t.resp),statusline:ZQ(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||QQ(i,t).bytes!==QQ(r,t).bytes)&&XQ(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=QQ(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:BA(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function t$(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const n$=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,r$=`#{session_id} #{client_control_mode} #{pane_id}`;function i$(e){let t=new Set;for(let n of e.split(`
|
|
499
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
500
|
-
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function
|
|
495
|
+
`}const $X=e=>({kind:`ok`,value:e}),eZ=e=>({kind:`failed`,reason:e});var tZ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const nZ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function rZ(e){return nZ.test(e)?e:null}function iZ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return $X(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return $X({app:n,missing:eZ(`its script could not be read (${r.reason})`)});let i=to(r.value);return $X({app:n,missing:i===null?eZ("its script is not one `cc-candybar install` wrote"):$X([i.node,i.script].filter(t=>!e.exists(t)))})}async function aZ(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function oZ(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${fr}://${Lr}/${n}`);return(r===null?await aZ(e,n):null)??{kind:`lost`,unopened:r,opener:iZ(e)}}function sZ(e,t,n){let r=ut({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?$X(r.stdout):eZ(r.stderr.trim()||r.error||r.reason)}const cZ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${fr}://probe"));u.isNil() ? "" : u.path.js`;async function lZ(){let e=await UX();if(e.kind!==`ok`)return eZ(ln(e).split(`
|
|
496
|
+
`).join(` — `));let t=WX(e.value,[`handlerProbes`]);if(t!==null)return eZ(t);let{version:n,handlerProbes:r}=e.value;return $X({version:n,arrivals:r})}function uZ(){return{platform:process.platform,sockets:{own:vt(),handler:yt()},now:Date.now,nonce:ne,daemon:lZ,open:e=>{let t=sZ(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=sZ(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,cZ]);if(e.kind===`failed`)return e;let t=e.value.trim();return $X(t===``?null:t)},script:e=>sZ(`doctor.osadecompile`,`/usr/bin/osadecompile`,[no(e)]),exists:p.existsSync}}const dZ=/^─{20,}/,fZ=/^❯(\s|$)/,pZ=/›\s*stashed$/;function mZ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>dZ.test(e)?[t]:[]).at(-2);return n===void 0||!fZ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function hZ(e){if(e.inMode)return{kind:`in-mode`};let t=mZ(e);return t===null?{kind:`no-prompt`}:pZ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function gZ(e){return/^❯\s*\S/u.test(mZ(e)?.prompt??``)}const _Z=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function vZ(e){return e.screen.some(e=>_Z.test(e))}const yZ={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function bZ(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function xZ(e,t,n){let r=bZ(t);if(r.kind===`refused`)return r;let i=r.hint,a=hZ(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:yZ[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function SZ(e,t,n,r){let i=SU(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function CZ(e){let t=SZ(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
|
|
497
|
+
`);return{inMode:n!==`0`,screen:r}}function wZ(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function TZ(e,t){let n=SZ(e,`claude-input.type`,wZ(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function EZ(){return{read:CZ,type:TZ}}function DZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function OZ(e){return kZ(()=>decodeURIComponent(e))}function kZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function AZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const jZ=(e,t)=>AZ(OZ(e),t),MZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,OZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},NZ=(e,t)=>AZ(OZ(e),t),PZ=(e,t)=>AZ(OZ(e),t),FZ=(e,t)=>{let n=DZ(OZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},IZ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=jV(XZ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}BZ(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},LZ=/^-?\d+$/;function RZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const zZ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!LZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=XZ(t,a),c=jV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&LZ.test(u)?VZ(l,parseInt(u,10)):HZ(`step-state`,r,l,PV(s,e=>t.sessionState.get(a,e),r)),f=RZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);BZ(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function BZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(_A));if(i.length===0)return;let a=uV(XZ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function VZ(e,t){return Math.max(e.min,Math.min(e.max,t))}function HZ(e,t,n,r){if(r===null)return n.min;if(!LZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return VZ(n,parseInt(r,10))}const UZ=`render-origin`;function WZ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function GZ(e){return JSON.stringify(e)}function KZ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function qZ(e,t){let n=JZ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function JZ(e,t){let n=e.sessionState.get(t,UZ);return n===null?null:WZ(KZ(n),e.sessionState,t)}function YZ(e,t,n){let r=JZ(e,t);if(r===null)return;let{path:i}=ZZ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function XZ(e,t){return e.configFor(qZ(e,t))}function ZZ(e){return sB(e.projectDir,e.cwd,e.configFile??void 0)}function QZ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const $Z=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=qZ(t,a),s=t.configFor(o),c=HF(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=ZZ(o),d=cV(s,e=>t.sessionState.get(a,e),r);iJ(QZ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},eQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!LZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=qZ(t,a),c=t.configFor(s),l=HF(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=ZZ(s),f=cV(c,e=>t.sessionState.get(a,e),r),p=rJ(d.path,f.key),m=typeof p==`number`?VZ(u,p):HZ(`step-config`,r,u,WF(f.globals,r)),h=RZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);iJ(QZ(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},tQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=oV(a,o),c=lV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=jV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});rQ(`save`,l,c);let d=ZZ(i);aJ(QZ(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(nQ)].join(` `)} → ${d.path} (session=${r})`)},nQ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Hg(e.value)}`;function rQ(e,t,n){for(let r of n){let n=t.validate(r.key,Hg(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const iQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=t.configFor(i),o=pV(a,e=>t.sessionState.get(r,e)),s=jV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});rQ(`save-preset`,s,o.placements);let l=ZZ(i),u=fJ(QZ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...hv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,pv.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(nQ)].join(` `)} → ${l.path} (session=${r})`)},aQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=hV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=ZZ(i);pJ(QZ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(oV(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ov.map(e=>pv[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${ov.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},oQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=qZ(t,i),o=ZZ(a);mJ(QZ(t,i),o,r),t.reloadConfig(a);let s=pv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},sQ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=qZ(t,i),o=HF(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=ZZ(a),l=r.map(gV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);lJ(QZ(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function cQ(e,t){let n=(e,t)=>[...Cg(Gy(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Hy(t.presets).flatMap(e=>n(t,e).map(t=>vA(nk(e),yg(t)))));return Hy(e.presets).flatMap(t=>n(e,t).map(e=>({member:vA(nk(t),yg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function lQ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[fA]:[]])}const uQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=qZ(t,a),s=t.configFor(o),c=HF(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=OF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=ZZ(o),f=hJ(QZ(t,a),d,r,u);t.reloadConfig(o);let p=lQ(cQ(s,t.configFor(o)),t.sessionState.get(a,fA)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},dQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n);t.journal.commit();let i=t.history.undo(r);YZ(t,r,i),t.dlog(`info`,`undo: restored ${LJ(i)} (session=${r})`)},fQ=(e,t)=>{let n=DZ(OZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,jV(XZ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},pQ=(e,t)=>{let n=DZ(OZ(e));t.journal.commit();let r=t.history.rewind(n);YZ(t,n,r),t.dlog(`info`,`rewind: put back ${LJ(r)||`nothing`} as edit mode found it (session=${n})`)},mQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n);t.journal.commit();let i=t.history.redo(r);YZ(t,r,i),t.dlog(`info`,`redo: re-applied ${LJ(i)} (session=${r})`)},hQ=(e,t)=>{DZ(OZ(e)),t.applyUpdate()},gQ=`client-hints`;function _Q(e,t){let n=e.sessionState.get(t,gQ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function vQ(e,t,n){let r=TM(n);e.sessionState.setBatch(t,UM(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${VM(n.nerdFont,n.marks)} ${jM(n.terminal,n.clicked)} ${MM(n.terminal,n.width)} ${NM(n.install)} ${FM(n.daemon)} ${IM(n.data)} ${BM(n.transcripts)} ${LM(n.frames,n.claudeSettings)} ${zM(n.claudeSettings.origin.sources)} (session=${t})`)}function yQ(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,CO(new Date)),i;try{i=zX(e.doctor,_Q(e,t),qZ(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:dY(n,r)},RX(t,r),fX(e.doctorStores))}catch(e){throw e instanceof sY?new J(e.message):e}return{...i,urlHandler:FX(e.arrival),install:uX(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:bQ(e,i)}}function bQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?wj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>aY(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const xQ=(e,t)=>{let n=DZ(OZ(e));vQ(t,n,yQ(t,n))},SQ=(e,t)=>{let n=rZ(OZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new J(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},CQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n),a=EM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=yQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=BX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Ij(s.fix)} (session=${i})`),vQ(t,i,c.value)},wQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=EM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!Nj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${Nj.join(` or `)}`);let s=yQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>nY(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),vQ(t,a,{...s,marks:u})},TQ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=qZ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=WL(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=OU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},_Q(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},EQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n),a=Object.values(t.configFor(qZ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=xZ(t.claudeInput,_Q(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},DQ=`config-override`,OQ=new Map([[gr,jZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=DZ(kZ(()=>decodeURIComponent(e.slice(0,n)))),i=kZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,DQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,DQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[_r,MZ],[mr,IZ],[hr,zZ],[xr,$Z],[Sr,eQ],[Dr,sQ],[Cr,tQ],[wr,iQ],[Tr,aQ],[Er,oQ],[Or,uQ],[kr,dQ],[Ar,mQ],[jr,fQ],[Mr,pQ],[yr,NZ],[br,PZ],[vr,FZ],[Nr,hQ],[Pr,xQ],[Fr,CQ],[Ir,wQ],[Lr,SQ],[Rr,TQ],[zr,EQ]]),kQ=new Set([mr,hr,xr,Sr,Dr,Cr,wr,Tr,Er,Or,kr,Ar,jr,Mr,vr,Nr,Pr,Fr,Ir,Rr,zr]),AQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Gr(Ur(e))){if(!i&&kQ.has(a)){let e=Vr(o);e.length>0&&e[0]&&(i=e[0])}let e=OQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&JJ(t.sessionState,i,n.join(`
|
|
498
|
+
`),CO(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function jQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const MQ=new Map([...OQ,[pr,AQ]].map(([e,t])=>[e,jQ(t)]));Object.freeze([...MQ.keys()]);const NQ=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),PQ=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],FQ=[[`workspace.added_dirs`,`string-list`]];function IQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of PQ){let i=zQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=LQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of FQ){let i=zQ(n,e),a=i===void 0?r:RQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))NQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function LQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function RQ(e){return Array.isArray(e)&&e.every(e=>LQ(e)===`string`)?`string-list`:LQ(e)}function zQ(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function BQ(e,t){switch(e){case`vars`:return{what:e,vars:VQ(t)};case`segments`:return{what:e,segments:KQ(t)};case`config`:return{what:e,config:XQ(t)}}}function VQ(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=WQ(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=HQ(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:UQ(r.lastUpdatedMs())})}return o}function HQ(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function UQ(e){return e===null?null:Math.max(0,Date.now()-e)}function WQ(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,GQ(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,GQ(i));return t}function GQ(e){return e.kind}function KQ(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=JQ(n),o=qQ(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:YQ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function qQ(e){let t=new Map;for(let n of Hy(e.presets))for(let r of Cg(Gy(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=yg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function JQ(e){let t=[],n=new Set;for(let r of Cg(Fy(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function YQ(e,t,n){let r=new Set;for(let i of pb(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function XQ(e){return e===null?null:e.config}const ZQ=[`vars`,`segments`,`config`];function QQ(e){return typeof e==`string`&&ZQ.includes(e)}function $Q(e){return Math.max(1,e-2)}const e$={moving:1e3/30,still:1e3},t$=1e3;function n$(e){return M_.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function r$(e,t){e.push(t);let n=e.findIndex(e=>e>t-t$);e.splice(0,n)}const i$=e=>({resp:e,bytes:JSON.stringify(e)}),a$=(e,t)=>j_[t].elsewhere===null?e.statusline:e.bar,o$=e=>Math.round(1e3/e);var s$=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return R_;let n=this.deps.now()-t$,r=this.shown(t);return L_(e=>{let i=t.rates.get(e);if(i===void 0)return F_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:o$(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=o$(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:i$(t.resp),statusline:i$(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||a$(i,t).bytes!==a$(r,t).bytes)&&r$(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=a$(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:KA(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function c$(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const l$=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,u$=`#{session_id} #{client_control_mode} #{pane_id}`;function d$(e){let t=new Set;for(let n of e.split(`
|
|
499
|
+
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function f$(e,t){let n=new Set;for(let r of e.split(`
|
|
500
|
+
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function p$(e,t){let n=new Map;for(let t of e.split(`
|
|
501
501
|
`)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
|
|
502
|
-
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var
|
|
503
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
504
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=N$(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[O$(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${d$} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,M$(n));if(r===null||this.closed)return null;let i=P$(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,m$(r),e])}),i!==n.status){let e=_$(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,u$,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,C$(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,F$(n));if(i===null)return;let a=I$(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,R$);if(r===null||this.closed)return;let i=z$(r[0]??``);if(n.kind===`none`&&H$(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&H$(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...f$,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${S$(`${this.deps.handler} ${V$(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,R$);if(r===null)return;let i=U$(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=U$(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,T$(t));return n.kind===`ok`?E$(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,T$(t)));return n.kind===`ok`?E$(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,x$(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,x$(t),n)))}};const G$=`CC_CANDYBAR_CONFIG`;function K$(e,t){return mz(t,e[G$])}const $=e=>({arity:e,keep:!0}),q$=e=>({arity:e,keep:!1}),J$={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":q$(`none`),"--background":q$(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":q$(`optional`),"-c":q$(`none`),"--continue":q$(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":q$(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":q$(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":q$(`none`),"--forward-subagent-text":$(`none`),"--from-pr":q$(`optional`),"-h":q$(`none`),"--help":q$(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":q$(`none`),"--print":q$(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":q$(`optional`),"--resume":q$(`optional`),"--safe-mode":$(`none`),"--session-id":q$(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":q$(`optional`),"--tmux":q$(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":q$(`none`),"--version":q$(`none`),"-w":q$(`optional`),"--worktree":q$(`optional`)},Y$={resume:`--resume`,fresh:`--session-id`};function X$(e){return[Y$[e.kind],e.sessionId]}const Z$=e=>e.startsWith(`-`)&&e!==`-`;function Q$(e,t){let n=t1(t);return n===null?{dir:e??t,args:[]}:e!==null&&$$(e,n.top)?{dir:e,args:[]}:{dir:e===null||t1(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const $$=(e,t)=>e===t||e.startsWith(t+s.sep);function e1(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!Z$(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=J$[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!Z$(e)):o.arity===`variadic`?n1(n.slice(r),e=>!Z$(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function t1(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function n1(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const r1=`candybar-band@cc-candybar`,i1=s.join(`bin`,`cc-candybar-native`),a1=`@cc-candybar-bar-pane`,o1=qM(`/reload-plugins`),s1=e=>({kind:`done`,said:e});function c1(e){let t=pZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const l1={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${T_.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,i1);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${r1} from ${r}`,finished:u1(e,r,n)}},off:()=>s1(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=c1(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${T_.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:p1(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>s1(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=c1(e),i=n.barPanes(r);return i.length>0?s1(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):s1(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=pZ(e.hints.tmux);if(r.kind===`refused`)return s1(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return s1(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>s1(`the daemon draws ${c1(e).pane}'s bar in its status line`),off:()=>s1(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function u1(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,r1],r);let i=mZ(n.claudeInput,e.hints.tmux,o1);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${r1} from ${t} and typed /reload-plugins into ${i.pane}`}const d1=new Set([ya,G$,...Mt]);function f1(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function p1(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${T_.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=v1(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${T_.statusline.label} off and on again`);let s=m1(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=e1(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=f1(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>d1.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...X$(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=h1(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(Q$(null,i.cwd),_))}let y=m(Q$(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${g1[g.kind](e.sessionId)}, and its statusline follows lane B`}function m1(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function h1(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const g1={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},_1={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function v1(e){let t=cZ(e);return t.kind===`ready`?dZ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:lZ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:_1[t.kind]}const y1={switches:Object.fromEntries(E_.map(e=>[e,!1])),revision:0};var b1=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??y1;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of E_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),VJ(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=l1[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function x1(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function S1(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function C1(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function w1(e,t,n){let r=x1(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const T1=2e3;function E1(e,t,n){let r=hU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function D1(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function O1(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const k1=`#{pane_id} #{${a1}}`;function A1(e,t){return e.split(`
|
|
505
|
-
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const
|
|
506
|
-
`);async function P1(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=D1(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,N1,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function F1(e,t){return D1(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function I1(e){let t=await gU(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await F1(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function L1(e){let{panePid:t,cwd:n,foreground:r}=await I1(e),i=await F1(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await P1(r),o=aY(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:M1(i,r,t)}}function R1(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function z1(e){return{claudeInput:yZ(),barPanes:e=>A1(E1(e,[`list-panes`,`-a`,`-F`,k1]),e.pane),openBarPane:(e,t,n)=>{let r=E1(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return E1(e,[`set-option`,`-p`,`-t`,r,a1,e.pane]),r},closePane:(e,t)=>void E1(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void D1(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:R1(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:Jz,paneClaude:L1,paneDir:async(e,t)=>{let n=Date.now()+T1;for(;;){let r=await I1(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${T1/1e3} s`);await ge(100)}},launcherNode:e=>w1(e,e=>S1(e,p.constants.X_OK),C1),onPath:(e,t)=>{let n=x1(e,t,e=>S1(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?O1(r.stdout):null;return i===null?(D1(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void E1(e,_Z(e.pane,`cc-candybar-lane`,[]),t)}}function B1(e,t){return E_.filter(n=>e[n]&&T_[n].elsewhere!==null&&t.has(n))}function V1(e,t){let n=`the bar is drawn in ${t.map(e=>T_[e].elsewhere).join(` and `)}`,r=Hr([{verb:Dr,args:[e,...t.map(e=>T_[e].setting)]}]);return{channels:[{severity:ny,message:n,lines:[[ry(n,Hr([{verb:gr,args:[n]}])),ry(`[⟲ draw it here]`,r)]]}]}}const H1={order:-1/0,text:null,failure:null};var U1=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??H1;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??H1;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function W1(e,t){for(let n of Object.entries(t))e.push(n)}const G1={ok:`info`,"bad-request":`warn`,threw:`error`};function K1(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function q1(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...K1(t)];return{level:G1[t.kind],line:`render${r.map(([e,t])=>` ${e}=${SM(t)}`).join(``)}`}}const J1=new iq,Y1=new JX,X1=new rj,Z1=i(import.meta.url),Q1=iX(gt());st(J1.launchStats);const $1=new aO({counters:J1,logger:M}),e0=PU({watchers:$1,logger:M}),{gitProvider:t0,usageStore:n0,mementoProvider:r0}=e0,i0=new sq,a0=new gJ(i0,M),o0=new zJ,s0=new Rv,c0=[t.execPath,...t.execArgv],l0=new b1({edge:z1(e=>d0.following(e)),host:{bundle:Z1,node:c0,socket:vt(),preload:$a(Z1)},state:i0,log:M,now:()=>_O(new Date),defer:e=>void pe(e)}),u0=new W$({edge:{run:(e,t,n)=>gU({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>hU({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>d0.subscribe(e,t),sessionInPane:(e,t)=>d0.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${je(vt())}`,...[...c0,Z1].map(je),`url-handle`].join(` `),owner:vt(),defer:e=>void pe(e),log:M}),d0=new e$({render:(e,t)=>Q0(e,t),watch:(e,t)=>(0,xb.reaction)(()=>i0.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>e2(e),shown:e=>f0.shown(e.hints.tmux),watching:()=>f0.follow(),periods:qQ,now:()=>performance.now(),log:M}),f0=new s$({listPanes:e=>gU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,n$]),listClients:e=>gU({socket:e},`frames.visibility`,[`list-clients`,`-F`,r$]),sockets:()=>new Set(d0.watched().flatMap(({req:e})=>p0(e))),onAnswer:(e,t)=>u0.answered(e,t),onChange:e=>d0.wakeWhere(t=>p0(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function p0({hints:{tmux:e}}){return e==null?[]:[e.socket]}const m0=new U1(At()),h0=new nq({gitService:t0,sessionState:i0,watchers:$1,log:M},{budgetBytes:()=>(O0(),KK(x0)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),g0=60*1e3,_0=YV({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:g0,stat:p.statSync,exit:()=>N0(0),log:M}),v0=KV({entryUrl:import.meta.url,intervalMs:g0,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>_0.checkNow(),log:M});let y0=null,b0=null,x0=0;function S0(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),N0(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),N0(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),N0(0)});try{k0(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),N0(1);return}y0=Oo(t.pid);let e=Ro(Bo(y0));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),N0(1);return}b0=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),i0.useStorage(new lq(wt(),500,M)),a0.useStorage(LJ(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),N0(0)}}),C0(E.createServer({allowHalfOpen:!1},e=>{P0(e)}),vt(),!1)}function C0(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),N0(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}w0(e,n)}),e.listen(n,()=>T0(n))}function w0(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),N0(1);return}}C0(e,n,!0)}function T0(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),N0(0);return}A0(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(x0)}MB`),nr();let r=m0.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),_0.arm(),v0.arm(),O0().arm(),E0(e,n.identity)}function E0(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>N0(e),log:M}).arm()}let D0=null;function O0(){if(D0===null)throw Error(`daemon: limits not yet established`);return D0}function k0(e){x0=Pn(e),D0=Vn(qn(J1.startedAt.getTime(),e=>N0(e),{limitBytes:x0}))}function A0(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:y0});n!==null&&M(`warn`,`lease write failed: ${n}`)}let j0=0,M0=!1;function N0(e){if(!M0){M0=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{u0.restoreAll(),t0.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{n0.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{$1.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{i0.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),b0!==null&&zo(b0,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function P0(e){j0++,J1.inFlight=j0;let t=!1,n=!0,r=()=>{n&&(n=!1,j0=Math.max(0,j0-1),J1.inFlight=j0)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>N0(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,J1.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,F0)},200),s=$t(e=>{H0(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(z0(e),null,F0)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,F0)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=t$(e),c=d0.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(vH[i](e,t))),refused:t=>e.end(Zt(t)),drawing:()=>!0});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const F0=()=>{},I0=e=>({resp:e,exitAfterFlush:null,delivered:F0}),L0=e=>({kind:`reply`,...e}),R0={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},z0=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),B0=(e,t)=>L0(I0({ok:!1,error:t,code:e,daemonV:3}));function V0(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return B0(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return B0(`VERSION_MISMATCH`,`this client's subscribe names no lane (${E_.join(`, `)}): it predates the lane toggles — update it`);let t=N_(e.lane);return t===null?B0(`BAD_REQUEST`,`subscribe needs a lane, one of ${E_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function H0(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?B0(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?V0(e):typeof e.kind!=`string`||!Object.hasOwn(R0,e.kind)?B0(`BAD_REQUEST`,`unknown kind`):L0(await U0(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:F0})}async function U0(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:F0};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return I0(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:d0.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return I0({ok:!0,stats:J1.snapshot({gitCache:t0.getStats(),usageCache:n0.getStats(),transcriptReads:ua(),renderCache:h0.stats,effectCache:s0.getStats(),sessionState:{sessions:i0.size(),observers:i0.observers(),revision:i0.latestRevision()},frameFeeds:d0.getStats(),tmuxStatus:u0.stats(),watchersActive:$1.size(),nextRestartReason:O0().describeNextRestart(),handlerProbes:Y1.list(),clients:X1.list(_O(new Date)),bundle:Z1,daemon:O0().serving(),doctorStores:aX(Q1)})});if(e.kind===`render`){let n=new Date,r=_O(n),i=n.getTime(),a=[],o=++J1.requestsTotal,s=t2(e),c=(e,t)=>X1.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:$A(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),d0.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await s2(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?F0:()=>HJ(i0,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:z0(e),delivered:F0})):n2(s.problems);l.outcome.kind!==`ok`&&J1.requestsErrored++,W1(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=q1(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return I0(X0(e.verb,e.value,{via:`link`,handler:Xt(e.clientVersion)}));if(e.kind===`debug`){if(!GQ(e.what))return I0({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${WQ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=h0.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?J0(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??rv(`colorCompatibility`)):q0};return I0({ok:!0,debug:NQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function W0(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:mz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const G0={sessionState:i0,dlog:M,applyUpdate:()=>v0.act(),doctor:hX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];h0.reload(...t);let n=h0.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:Q1,probes:Y1,clients:X1,bundle:Z1,serving:()=>O0().serving(),memento:r0,claudeInput:yZ(),history:a0,navigation:o0,configFor:e=>h0.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>h0.reload(e.projectDir,e.cwd,e.configFile??void 0)};G0.reloadConfig;const K0={endcaps:rv(`endcaps`),colorCompatibility:rv(`colorCompatibility`),wrap:rv(`autoWrap`),padding:rv(`padding`),width:1/0},q0=new Map;function J0(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Zv(i,{...K0,colorCompatibility:t}));return n}const Y0={...e0,history:e=>a0.depth(e),feeds:e=>d0.feedsOf(e)};function X0(e,t,n){if(e===`tmux-status-click`)return Z0(t);let r=TQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...G0,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function Z0(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=u0.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=fo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):X0(e.verb,e.value,{via:`tmux-status`})}let i=ut({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}async function Q0(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await r2(e,_O(n),r,{by:`feed`,fps:t}),s=m0.linkFor(e.hookData.session_id,a2(i)),c=e.hookData.session_id,l=i2(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:c2(c,i,s,l,B1(o,d0.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=q1(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=z0(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function $0(e,t){return HB(t.config,t=>i0.get(e,t),e=>t.authoredRoots.has(e))}function e2(e){try{var t=na();let n=e.hookData.session_id,r=LZ(e.requested,i0,n);return BB($0(n,t.u(h0.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function t2(e){let{report:t}=kQ(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=W0(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:QA(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const n2=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:F0});async function r2(e,t,n,r){try{var i=na();W1(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);W1(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=LZ(e.requested,i0,a),{entry:u,state:d}=i.u(h0.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=KQ(f??120),m=Qv(o.termRows);W1(n,{width:String(p)});let h=t=>i0.get(e.hookData.session_id,t),g=$0(a,d),_=BB(g);W1(n,{lanes:E_.filter(e=>_[e]).join(`,`)||`-`}),l0.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:XA(e.hookData)},_,a0.revision(a)),u0.observe(a,o.tmux,_.tmuxStatus);let v=await sW(e.hookData,t,{...Y0,navigation:e=>o0.depth(e,i0,wV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...dV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});W1(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:WU(v.git),feeds:YQ(v.feeds)});let y=[],b=VU(g,p),ee=s0.of(a),x=NK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=WJ(i0,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
|
|
507
|
-
`),re=
|
|
508
|
-
`)),T=
|
|
509
|
-
`}function
|
|
510
|
-
`);return}t.stdout.write(
|
|
511
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
502
|
+
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var m$=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${w(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:f$(t.stdout,d$(n.stdout)),status:p$(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!h$(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function h$(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const g$=`@cc-candybar-status-prior`,_$=`@cc-candybar-status-wrote`,v$=`@cc-candybar-binding-prior`,y$=[`-T`,`root`,`MouseDown1Status`],b$=Array.from({length:5},(e,t)=>t),x$=e=>`@cc-candybar-row-${e}`,S$=e=>`#[fill=terminal]#{${x$(e)}}`,C$=e=>`status-format[${e}]`;function w$(e){return e===0?`off`:e===1?`on`:String(e)}function T$(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function E$(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function D$(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function O$(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function k$(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function A$(e){return e.map(e=>e.map(k$).join(` `)).join(` ; `)}const j$=`ccb:separator`;function M$(e){return O$(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,j$],e]))}function N$(e,t){let n=e.split(`${j$}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const P$=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],F$=e=>[`show-options`,`-g`,`-q`,`-v`,e],I$=e=>[[`show-options`,`-t`,e],P$(e,`status`),...b$.map(t=>P$(e,C$(t)))];function L$(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
503
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of b$)i.includes(C$(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function R$(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,C$(Number(t)),D$(n)])]}const z$=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...I$(e),...b$.map(e=>F$(C$(e))),P$(e,g$),P$(e,_$)];function B$(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:T$(t)}catch(e){return{kind:`theirs`,why:`${g$} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function V$(e,t,n){let[r=``,...i]=t,a=L$(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return B$(s,c,n);let l=T$(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,S$(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,g$,JSON.stringify(f)],...R$(e,d)]}}const H$=e=>[...I$(e),P$(e,_$)];function U$(e,t,n){let r=L$(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(E$(r.formats,t.wrote))a.push(...R$(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,C$(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,D$(t.status)]):o.push(`status`)),a.push(...b$.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,x$(t)]),[`set-option`,`-q`,`-u`,`-t`,e,g$],[`set-option`,`-q`,`-u`,`-t`,e,_$]),{commands:a,kept:o}}const W$=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,G$=[[`list-keys`,`-T`,`root`]];function K$(e){let t=W$.exec(e);return t===null?null:{line:t[0],command:t[1]}}const q$=`cc-candybar://tmux-status-click/`,J$=e=>`${q$}${Br([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,Y$=e=>e?.command.includes(q$)??!1;function X$(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,v$]};return Y$(K$(t))?{steps:[e===null?{command:[`unbind-key`,...y$]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var Z$=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),this.deps.defer(()=>{this.held.get(e)===a&&(a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=wH(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)}))})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[e,t]of this.servers){for(let[n,r]of[...t.layouts]){t.layouts.delete(n);let i=this.askSync(e,H$(n));if(i===null)continue;let a=U$(n,r.prior,i);this.writeSync(e,a.commands),this.saidRestored(e,n,a.kept)}let n=t.binding;if(t.binding={kind:`none`},n.kind===`ours`||n.kind===`adopted`){let t=this.askSync(e,G$);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let[t,n,r,...i]=Vr(e);if(t===void 0||n===void 0||r===void 0||i.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let a=[...this.held.values()].find(e=>e.socket===t&&e.pane===`%${n}`)?.frame?.links[r];return a===void 0?{kind:`refused`,reason:`pane %${n}'s status line draws no link ${r} now`}:{kind:`link`,url:a}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${g$}}\t#{${_$}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
504
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=B$(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[F$(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${v$} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,z$(n));if(r===null||this.closed)return null;let i=V$(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,x$(r),e])}),i!==n.status){let e=w$(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,_$,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,A$(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,H$(n));if(i===null)return;let a=U$(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,G$);if(r===null||this.closed)return;let i=K$(r[0]??``);if(n.kind===`none`&&Y$(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&Y$(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...y$,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${k$(`${this.deps.handler} ${J$(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,G$);if(r===null)return;let i=X$(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=X$(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,M$(t));return n.kind===`ok`?N$(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,M$(t)));return n.kind===`ok`?N$(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,O$(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,O$(t),n)))}};const Q$=`CC_CANDYBAR_CONFIG`;function $$(e,t){return xz(t,e[Q$])}const $=e=>({arity:e,keep:!0}),e1=e=>({arity:e,keep:!1}),t1={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":e1(`none`),"--background":e1(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":e1(`optional`),"-c":e1(`none`),"--continue":e1(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":e1(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":e1(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":e1(`none`),"--forward-subagent-text":$(`none`),"--from-pr":e1(`optional`),"-h":e1(`none`),"--help":e1(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":e1(`none`),"--print":e1(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":e1(`optional`),"--resume":e1(`optional`),"--safe-mode":$(`none`),"--session-id":e1(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":e1(`optional`),"--tmux":e1(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":e1(`none`),"--version":e1(`none`),"-w":e1(`optional`),"--worktree":e1(`optional`)},n1={resume:`--resume`,fresh:`--session-id`};function r1(e){return[n1[e.kind],e.sessionId]}const i1=e=>e.startsWith(`-`)&&e!==`-`;function a1(e,t){let n=c1(t);return n===null?{dir:e??t,args:[]}:e!==null&&o1(e,n.top)?{dir:e,args:[]}:{dir:e===null||c1(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const o1=(e,t)=>e===t||e.startsWith(t+s.sep);function s1(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!i1(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=t1[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!i1(e)):o.arity===`variadic`?l1(n.slice(r),e=>!i1(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function c1(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function l1(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const u1=`candybar-band@cc-candybar`,d1=s.join(`bin`,`cc-candybar-native`),f1=`@cc-candybar-bar-pane`,p1=$M(`/reload-plugins`),m1=e=>({kind:`done`,said:e});function h1(e){let t=bZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const g1={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${j_.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,d1);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${u1} from ${r}`,finished:_1(e,r,n)}},off:()=>m1(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=h1(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${j_.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:b1(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>m1(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=h1(e),i=n.barPanes(r);return i.length>0?m1(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):m1(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=bZ(e.hints.tmux);if(r.kind===`refused`)return m1(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return m1(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>m1(`the daemon draws ${h1(e).pane}'s bar in its status line`),off:()=>m1(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function _1(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,u1],r);let i=xZ(n.claudeInput,e.hints.tmux,p1);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${u1} from ${t} and typed /reload-plugins into ${i.pane}`}const v1=new Set([ya,Q$,...Mt]);function y1(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function b1(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${j_.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=T1(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${j_.statusline.label} off and on again`);let s=x1(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=s1(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=y1(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>v1.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...r1(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=S1(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(a1(null,i.cwd),_))}let y=m(a1(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${C1[g.kind](e.sessionId)}, and its statusline follows lane B`}function x1(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function S1(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const C1={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},w1={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function T1(e){let t=hZ(e);return t.kind===`ready`?vZ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:gZ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:w1[t.kind]}const E1={switches:Object.fromEntries(M_.map(e=>[e,!1])),revision:0};var D1=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??E1;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of M_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),JJ(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=g1[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function O1(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function k1(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function A1(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function j1(e,t,n){let r=O1(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const M1=2e3;function N1(e,t,n){let r=SU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function P1(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function F1(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const I1=`#{pane_id} #{${f1}}`;function L1(e,t){return e.split(`
|
|
505
|
+
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const R1=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function z1(e,t,n){for(let r of pY(fY(e),t)){if(r.command.split(` `).some(e=>R1.test(e)))return!0;if(r.pid===n)return!1}return!1}const B1=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
|
|
506
|
+
`);async function V1(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=P1(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,B1,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function H1(e,t){return P1(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function U1(e){let t=await CU(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await H1(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function W1(e){let{panePid:t,cwd:n,foreground:r}=await U1(e),i=await H1(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await V1(r),o=fY(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:z1(i,r,t)}}function G1(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function K1(e){return{claudeInput:EZ(),barPanes:e=>L1(N1(e,[`list-panes`,`-a`,`-F`,I1]),e.pane),openBarPane:(e,t,n)=>{let r=N1(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return N1(e,[`set-option`,`-p`,`-t`,r,f1,e.pane]),r},closePane:(e,t)=>void N1(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void P1(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:G1(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:tB,paneClaude:W1,paneDir:async(e,t)=>{let n=Date.now()+M1;for(;;){let r=await U1(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${M1/1e3} s`);await ge(100)}},launcherNode:e=>j1(e,e=>k1(e,p.constants.X_OK),A1),onPath:(e,t)=>{let n=O1(e,t,e=>k1(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?F1(r.stdout):null;return i===null?(P1(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void N1(e,wZ(e.pane,`cc-candybar-lane`,[]),t)}}function q1(e,t){return M_.filter(n=>e[n]&&j_[n].elsewhere!==null&&t.has(n))}function J1(e,t){let n=`the bar is drawn in ${t.map(e=>j_[e].elsewhere).join(` and `)}`,r=Hr([{verb:Dr,args:[e,...t.map(e=>j_[e].setting)]}]);return{channels:[{severity:cy,message:n,lines:[[ly(n,Hr([{verb:gr,args:[n]}])),ly(`[⟲ draw it here]`,r)]]}]}}const Y1={order:-1/0,text:null,failure:null};var X1=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??Y1;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??Y1;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function Z1(e,t){for(let n of Object.entries(t))e.push(n)}const Q1={ok:`info`,"bad-request":`warn`,threw:`error`};function $1(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function e0(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...$1(t)];return{level:Q1[t.kind],line:`render${r.map(([e,t])=>` ${e}=${OM(t)}`).join(``)}`}}const t0=new dq,n0=new tZ,r0=new lj,i0=i(import.meta.url),a0=dX(gt());st(t0.launchStats);const o0=new dO({counters:t0,logger:M}),s0=VU({watchers:o0,logger:M}),{gitProvider:c0,usageStore:l0,mementoProvider:u0}=s0,d0=new mq,f0=new CJ(d0,M),p0=new KJ,m0=new Wv,h0=[t.execPath,...t.execArgv],g0=new D1({edge:K1(e=>v0.following(e)),host:{bundle:i0,node:h0,socket:vt(),preload:$a(i0)},state:d0,log:M,now:()=>CO(new Date),defer:e=>void pe(e)}),_0=new Z$({edge:{run:(e,t,n)=>CU({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>SU({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>v0.subscribe(e,t),sessionInPane:(e,t)=>v0.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${je(vt())}`,...[...h0,i0].map(je),`url-handle`].join(` `),owner:vt(),defer:e=>void pe(e),log:M}),v0=new s$({render:(e,t)=>a2(e,t),watch:(e,t)=>(0,Db.reaction)(()=>d0.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>s2(e),shown:e=>y0.shown(e.hints.tmux),watching:()=>y0.follow(),periods:e$,now:()=>performance.now(),log:M}),y0=new m$({listPanes:e=>CU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,l$]),listClients:e=>CU({socket:e},`frames.visibility`,[`list-clients`,`-F`,u$]),sockets:()=>new Set(v0.watched().flatMap(({req:e})=>b0(e))),onAnswer:(e,t)=>_0.answered(e,t),onChange:e=>v0.wakeWhere(t=>b0(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function b0({hints:{tmux:e}}){return e==null?[]:[e.socket]}const x0=new X1(At()),S0=new lq({gitService:c0,sessionState:d0,watchers:o0,log:M},{budgetBytes:()=>(F0(),$K(O0)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),C0=60*1e3,w0=nH({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:C0,stat:p.statSync,exit:()=>B0(0),log:M}),T0=$V({entryUrl:import.meta.url,intervalMs:C0,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>w0.checkNow(),log:M});let E0=null,D0=null,O0=0;function k0(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),B0(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),B0(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),B0(0)});try{I0(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),B0(1);return}E0=Oo(t.pid);let e=Ro(Bo(E0));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),B0(1);return}D0=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),d0.useStorage(new gq(wt(),500,M)),f0.useStorage(WJ(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),B0(0)}}),A0(E.createServer({allowHalfOpen:!1},e=>{V0(e)}),vt(),!1)}function A0(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),B0(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}j0(e,n)}),e.listen(n,()=>M0(n))}function j0(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),B0(1);return}}A0(e,n,!0)}function M0(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),B0(0);return}L0(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(O0)}MB`),nr();let r=x0.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),w0.arm(),T0.arm(),F0().arm(),N0(e,n.identity)}function N0(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>B0(e),log:M}).arm()}let P0=null;function F0(){if(P0===null)throw Error(`daemon: limits not yet established`);return P0}function I0(e){O0=Pn(e),P0=Vn(qn(t0.startedAt.getTime(),e=>B0(e),{limitBytes:O0}))}function L0(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:E0});n!==null&&M(`warn`,`lease write failed: ${n}`)}let R0=0,z0=!1;function B0(e){if(!z0){z0=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{_0.restoreAll(),c0.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{l0.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{o0.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{d0.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),D0!==null&&zo(D0,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function V0(e){R0++,t0.inFlight=R0;let t=!1,n=!0,r=()=>{n&&(n=!1,R0=Math.max(0,R0-1),t0.inFlight=R0)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>B0(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,t0.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,H0)},200),s=$t(e=>{Y0(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(K0(e),null,H0)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,H0)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=c$(e),c=v0.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(TH[i](e,t))),refused:t=>e.end(Zt(t)),drawing:()=>!0});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const H0=()=>{},U0=e=>({resp:e,exitAfterFlush:null,delivered:H0}),W0=e=>({kind:`reply`,...e}),G0={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},K0=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),q0=(e,t)=>W0(U0({ok:!1,error:t,code:e,daemonV:3}));function J0(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return q0(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return q0(`VERSION_MISMATCH`,`this client's subscribe names no lane (${M_.join(`, `)}): it predates the lane toggles — update it`);let t=z_(e.lane);return t===null?q0(`BAD_REQUEST`,`subscribe needs a lane, one of ${M_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function Y0(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?q0(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?J0(e):typeof e.kind!=`string`||!Object.hasOwn(G0,e.kind)?q0(`BAD_REQUEST`,`unknown kind`):W0(await X0(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:H0})}async function X0(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:H0};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return U0(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:v0.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return U0({ok:!0,stats:t0.snapshot({gitCache:c0.getStats(),usageCache:l0.getStats(),transcriptReads:ua(),renderCache:S0.stats,effectCache:m0.getStats(),sessionState:{sessions:d0.size(),observers:d0.observers(),revision:d0.latestRevision()},frameFeeds:v0.getStats(),tmuxStatus:_0.stats(),watchersActive:o0.size(),nextRestartReason:F0().describeNextRestart(),handlerProbes:n0.list(),clients:r0.list(CO(new Date)),bundle:i0,daemon:F0().serving(),doctorStores:fX(a0)})});if(e.kind===`render`){let n=new Date,r=CO(n),i=n.getTime(),a=[],o=++t0.requestsTotal,s=c2(e),c=(e,t)=>r0.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:aj(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),v0.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await m2(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?H0:()=>YJ(d0,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:K0(e),delivered:H0})):l2(s.problems);l.outcome.kind!==`ok`&&t0.requestsErrored++,Z1(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=e0(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return U0(r2(e.verb,e.value,{via:`link`,handler:Xt(e.clientVersion)}));if(e.kind===`debug`){if(!QQ(e.what))return U0({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${ZQ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=S0.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?t2(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??lv(`colorCompatibility`)):e2};return U0({ok:!0,debug:BQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function Z0(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:xz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const Q0={sessionState:d0,dlog:M,applyUpdate:()=>T0.act(),doctor:SX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];S0.reload(...t);let n=S0.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:a0,probes:n0,clients:r0,bundle:i0,serving:()=>F0().serving(),memento:u0,claudeInput:EZ(),history:f0,navigation:p0,configFor:e=>S0.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>S0.reload(e.projectDir,e.cwd,e.configFile??void 0)};Q0.reloadConfig;const $0={endcaps:lv(`endcaps`),colorCompatibility:lv(`colorCompatibility`),wrap:lv(`autoWrap`),padding:lv(`padding`),width:1/0},e2=new Map;function t2(e,t){let n=new Map;for(let[r,i]of e)n.set(r,ry(i,{...$0,colorCompatibility:t}));return n}const n2={...s0,history:e=>f0.depth(e),feeds:e=>v0.feedsOf(e)};function r2(e,t,n){if(e===`tmux-status-click`)return i2(t);let r=MQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...Q0,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function i2(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=_0.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=fo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):r2(e.verb,e.value,{via:`tmux-status`})}let i=ut({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}async function a2(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await u2(e,CO(n),r,{by:`feed`,fps:t}),s=x0.linkFor(e.hookData.session_id,f2(i)),c=e.hookData.session_id,l=d2(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:h2(c,i,s,l,q1(o,v0.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=e0(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=K0(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function o2(e,t){return YB(t.config,t=>d0.get(e,t),e=>t.authoredRoots.has(e))}function s2(e){try{var t=na();let n=e.hookData.session_id,r=WZ(e.requested,d0,n);return qB(o2(n,t.u(S0.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function c2(e){let{report:t}=IQ(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=Z0(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:ij(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const l2=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:H0});async function u2(e,t,n,r){try{var i=na();Z1(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);Z1(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=WZ(e.requested,d0,a),{entry:u,state:d}=i.u(S0.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=$Q(f??120),m=iy(o.termRows);Z1(n,{width:String(p)});let h=t=>d0.get(e.hookData.session_id,t),g=o2(a,d),_=qB(g);Z1(n,{lanes:M_.filter(e=>_[e]).join(`,`)||`-`}),g0.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:nj(e.hookData)},_,f0.revision(a)),_0.observe(a,o.tmux,_.tmuxStatus);let v=await mW(e.hookData,t,{...n2,navigation:e=>p0.depth(e,d0,jV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...vV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});Z1(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:ZU(v.git),feeds:n$(v.feeds)});let y=[],b=JU(g,p),ee=m0.of(a),x=BK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=ZJ(d0,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
|
|
507
|
+
`),re=T0.notice({sessionId:a,dismissed:d0.get(a,LV),enabled:g.updateNotice}),ie=u.lastError===null?null:u.failedFile,ae=[...u.lastWarning===null?[]:[{kind:`load`,message:u.lastWarning}],...y],w=uy(C,re,ae.map(e=>e.message).join(`
|
|
508
|
+
`)),T=c0.getStats(),oe=l0.getStats(),E=ee.lastFrame(),se=E.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ce=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,le=ae.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return Z1(n,{git:`${T.size}/${T.hits}h/${T.misses}m`,usage:`${oe.size}/${oe.hits}h/${oe.misses}m`,effect:E.effect,effectT:E.t.toFixed(3),effectRows:`${E.made}made/${E.reused}reused`,effectOwn:se,fadeBasis:E.basis,stateRev:String(E.revision),fades:ce(E.fades),leaves:ce(E.leaves),motion:x.motion,err:C?`Y`:`N`,clickError:S.kind===`none`?`-`:S.kind,upd:String(re.length),warn:le}),{drawn:{body:x.text,diagnostics:w,failedConfigFile:ie,geometry:{width:p,rowCap:m,colorCompatibility:g.colorCompatibility}},motion:x.motion,clickShown:te,lanes:_}}catch(e){i.e=e}finally{i.d()}}function d2(e,t){return py(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
|
|
509
|
+
`}function f2(e){return e.diagnostics===null?null:fy(e.diagnostics)}function p2(e){let t=e.hookData.session_id,{client:n,...r}=e.hints,i=JSON.stringify(r);d0.get(t,`client-hints`)!==i&&d0.set(t,gQ,i);let a=GZ(e.requested);d0.get(t,`render-origin`)!==a&&d0.set(t,UZ,a)}async function m2(e,t,n,r){p2(e);let{drawn:i,motion:a,clickShown:o,lanes:s}=await u2(e,n,r,N_),{link:c,failure:l}=x0.sync(e.hookData.session_id,t,f2(i));Z1(r,{dumpFailed:l===null?`-`:JSON.stringify(l)});let u=d2(i,c),d=e.hookData.session_id,f=q1(s,v0.following(d)),p=h2(d,i,c,u,f),m=cj(e.hints.client??null)===`statusline`;return Z1(r,{handoff:(m?f:[]).join(`,`)||`-`}),{answer:m?p:u,motion:a,clickShown:o}}function h2(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:d2({...t,body:my(J1(e,[a,...o]),t.geometry)},n)}const g2={connectMs:200,budgetMs:500};async function _2(e,n){let r=n.includes(`--json`),i=await v2(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${ln(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
510
|
+
`);return}t.stdout.write(y2(i.value))}function v2(e){return nn({kind:`debug`,what:e},g2,e=>`debug`in e?e.debug:void 0)}function y2(e){switch(e.what){case`vars`:return b2(e.vars);case`segments`:return x2(e.segments);case`config`:return S2(e.config);default:return e}}function b2(e){if(e.length===0)return`no variables (DSL not active)
|
|
511
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${w2(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${C2(a.value)}${e}${o}`)}return t.join(`
|
|
512
512
|
`)+`
|
|
513
|
-
`}function
|
|
513
|
+
`}function x2(e){if(e.length===0)return`no segments (DSL not active)
|
|
514
514
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
515
515
|
`)+`
|
|
516
|
-
`}function
|
|
516
|
+
`}function S2(e){return e===null?`config: DSL not active
|
|
517
517
|
`:JSON.stringify(e,null,2)+`
|
|
518
|
-
`}function
|
|
518
|
+
`}function C2(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function w2(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function T2(){let e=D2();return e===null?null:p.readFileSync(e,`utf-8`)}function E2(){let e;try{e=T2()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function D2(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const O2=5e3;function k2(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:sN(4e5,1e6),...YU(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:bv(()=>!0),themeDefault:e.theme.kind===`decided`?{differs:!0,theme:e.theme.name}:{differs:!1},resumeCommand:qU(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function A2(e,t){let n=aB(e,e),r=cB(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function j2(e,n=t.cwd()){let r=[],i=xz(n,e)??null,a=i===null?A2(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=uB(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await P2(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Jg&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Jg||e instanceof Error?e.message:String(e),warnings:r})}}async function M2(e,t,n){let r=vB(e,VB,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new QK,o=new qO(a,i.globals.default_empty_value??``,void 0,new mq);try{let s=EK(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(O2);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${O2} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function N2({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:zK(t,n,r,i,k2(a,e.at(-1)??null,s),s,JU(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}}},a),failures:c,advisories:l}}async function P2(e,t,n){let r=await M2(e,t,n),{config:i}=r,a=CO(new Date);try{let e=QV();try{jV(i),HF(i)}finally{e()}let t=Uy(null,i.globals.preset,i.presets),o=(e,t)=>{let n=YB(i,t=>t===`preset`?e:null,()=>t),o;try{o=N2(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Hy(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
519
519
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
520
|
-
`));return d}finally{r.registry.dispose()}}function
|
|
521
|
-
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${
|
|
522
|
-
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
523
|
-
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:
|
|
520
|
+
`));return d}finally{r.registry.dispose()}}function F2(e){return e.map(e=>`warning: ${e}\n`).join(``)}function I2(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:F2(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:F2(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const L2=`--render`,R2=`Usage: cc-candybar check [${L2}] [config-file]\n`;function z2(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==L2);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${R2}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${R2}`}:{kind:`run`,target:n[0],render:t.includes(L2)}}async function B2(e){let n=z2(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:I2(await j2(n.target??$$(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const V2=/^[a-z][a-z0-9+.-]*:\/\//i,H2=/^[^@\s/]+@[^:\s/]+:/,U2=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function W2(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function G2(e,t,n){let r=bz(t,e);if(n(r))return{kind:`path`,dir:r};if(V2.test(e)||H2.test(e))return{kind:`git`,url:e,shown:W2(e)};let i=U2.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function K2(e,t){let n=s.join(e,Xz),r=$z(n);if(`error`in r)throw Error(`${t}: could not list ${Xz}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${Xz}/<name>/${wz}`);return r.folders.map(e=>s.join(n,e,wz))}function q2(e,t,n){let r=(n,...r)=>{let i=ut({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
|
|
521
|
+
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${Xz}/`)}function J2(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return q2(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function Y2(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function X2(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,wz),s.join(t,wz));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function Z2(e,t,n){let r=K2(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,wz))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=gB(a.map(e=>s.join(e,wz)),VB,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(Xz,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,Xz))}`).join(`
|
|
522
|
+
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:Y2(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)X2(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,wz),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function Q2(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=G2(n,process.cwd(),zO);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=J2(i,t=>Z2(t,Yz(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function $2(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const e4=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function t4(e,t,n){return{termCols:$2(e.COLUMNS,n.columns),termRows:$2(e.LINES,n.rows),ssh:e4.some(t=>(e[t]??``)!==``),tmux:ej(e),configEnv:$$(e,t),claudeConfigDir:ba(e,t),mementoEnv:Nt(e,t),terminalEnv:Ft(e)}}function n4(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function r4(e){let t=WX(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=n4(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:tn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const i4=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},a4=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function o4(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function s4(e){let t=WX(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=o4(n?.postMortems,e=>Array.isArray(e)&&e.every(i4)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&a4(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function c4(e,t,n){let r=WX(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=n4(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const l4=e=>sj.includes(e.role),u4=e=>c4(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&rj.includes(e.rateLimits),`the rate-limit windows they carried`),d4=e=>c4(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),f4=e=>c4(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&l4(e)&&oj.includes(e.frame),`what they drew and from which project`),p4=e=>c4(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&l4(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function m4(e,t,n){let r=e.doctorStores?.[t],i=o4(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function h4(e){let t=WX(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:m4(e,`marks`,tY),clicked:m4(e,`clicked`,iY),postMortemsRead:m4(e,`postMortemsRead`,oX)}}async function g4(){let e=await UX();if(e.kind!==`ok`){let t={kind:`failed`,reason:ln(e).split(`
|
|
523
|
+
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:r4(e.value),rateLimits:u4(e.value),transcripts:d4(e.value),frames:f4(e.value),widths:p4(e.value),serving:s4(e.value),stores:h4(e.value)}}const _4=` (fix: click the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,v4=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor`;function y4({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:_4}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${v4}\n`)}function b4(e){let t={sessionState:new mq},n=sq(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??cq(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function x4(e,t,n){return n.kind===`failed`?n:uX(e,n.value.bundle,lY(t,n.value.clients).map(({client:e})=>e))}function S4(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:lY(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function C4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:lY(e,t.value).map(e=>e.transcript)}}function w4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:dY(e,t.value)}}function T4(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:RX(e.sessionId,lY(e,t.value))}async function E4(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=t4(r,i,a()),u=cY(r.CLAUDE_CODE_SESSION_ID);s={...zX(e,l,{projectDir:uY(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:xz(i,o)??$$(r,i)??null},()=>null,c.serving,S4(u,c.rateLimits,xa(l.claudeConfigDir)),C4(u,c.transcripts),u,w4(u,c.frames),T4(u,c.widths,l.termCols??null),c.stores),urlHandler:await oZ(t),install:x4(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=TM(s);return{stdout:c.map(y4).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function D4(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new _e(e),{columns:r}=n;return n.destroy(),{columns:r}}async function O4(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
|
|
524
524
|
Usage: cc-candybar doctor [config-file]
|
|
525
|
-
`),t.exit(2));let n=t.cwd(),r=await
|
|
526
|
-
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const
|
|
527
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
525
|
+
`),t.exit(2));let n=t.cwd(),r=await E4(SX(b4),uZ(),g4,t.env,n,D4,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function k4(e){return!e.ok&&e.code!==`RENDER_FAILED`}function A4(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=E.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Zt(c))),s.on(`data`,$t(e=>{let t=e;k4(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function j4(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function M4(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function N4(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=A4(e,t,n,e=>{s=j4(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=M4(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&Jn();let e=s;s=j4(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function P4(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function F4(e,n){let{values:r,tokens:i}=T({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=z_(r.lane);c===null&&(s(`--lane needs one of ${M_.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=c$(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{P4(p,e)&&t(),p=e},h=async e=>{let r=await mn(e,a,o,{...t4(t.env,o,t.stderr),client:Lt(`frames`,n)});r.kind!==`ok`&&(s(ln(r)),r.kind===`transient`&&Jn())},g=e=>{f?.close(),f=N4(vt(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of ve({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function I4(e){let t=e.replace(/\n+$/,``).split(`
|
|
526
|
+
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const L4=5e3,R4=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function z4(e,t,n,r){let i=e.split(`
|
|
527
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?f$(e,d$(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function B4(e,t){let[n,r]=await Promise.all([CU(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,l$]),CU(e,`bar-pane.tmux`,[`list-clients`,`-F`,u$])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:z4(n.stdout,r.stdout,t,e.pane)}:r:n}function V4(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>L4)throw Error(`tmux has not answered for ${L4/1e3} s: ${t.reason}`)}}function H4(e){let{positionals:t}=(()=>{try{return T({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${R4}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(R4);return{pane:n}}async function U4(e){try{return await W4(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function W4(e){let{pane:n}=H4(e),r=ej(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await B4(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=V4(),f=async()=>{if(a.kind!==`shown`)return;let e=I4(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await CU(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:N4(vt(),e,`pane`,{frame:e=>n(oH(pn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=V4();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await hn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${vt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(Jn(),u=``),c=ln(e))}h(),await ge(500);let e=await B4(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const G4=i(import.meta.url),K4=e=>e.some(e=>t.argv.includes(e));function q4(){console.log(ZA);let e=$a(G4),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${j_.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Re(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const J4={install:async e=>{await go(e,G4),t.exit(0)},"install-url-handler":async()=>{uo(G4),t.exit(0)},"url-handle":async e=>{await po(e[0])},daemon:async()=>{k0()},"daemon-stats":async e=>{await HX(e),t.exit(0)},frames:async()=>{await F4(t.argv,G4)},check:async e=>{await B2(e)},lint:async e=>{await B2(e)},plugin:async e=>{t.exit(Q2(e))},schema:async()=>{E2()},doctor:async e=>{await O4(e)},"bar-pane":async e=>{t.exit(await U4(e))},...Object.fromEntries(ZQ.map(e=>[e,async n=>{await _2(e,n),t.exit(0)}]))};async function Y4(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(J4,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),K4(FA.help)&&(q4(),t.exit(0)),K4(FA.version)&&(console.log(`cc-candybar ${qe}`),t.exit(0)),n!==null){await J4[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
528
528
|
|
|
529
529
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
530
530
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -540,4 +540,4 @@ Add to ~/.claude/settings.json:
|
|
|
540
540
|
Run with --help for more options.
|
|
541
541
|
|
|
542
542
|
To test output manually:
|
|
543
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
543
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),q4(),t.exit(1));let i=oH(await mn(r,t.argv.slice(1),t.cwd(),{...t4(t.env,t.cwd(),t.stderr),client:Lt(`node`,G4)}));i.debug!==null&&D(i.debug),i.kick&&Jn(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}Y4();export{};
|