@promptctl/cc-candybar 1.219.0 → 1.219.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 +77 -77
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o from"node:os";import s,{closeSync as c,constants as l,existsSync as u,fstatSync as d,linkSync as f,mkdtempSync as p,openSync as m,readFileSync as h,readSync as g,rmSync as _,statSync as v,writeFileSync as y}from"node:fs";import{StringDecoder as b}from"node:string_decoder";import{inspect as x,parseArgs as S,types as C}from"node:util";import{clearImmediate as w,setImmediate as T}from"node:timers";import{spawn as ee,spawnSync as te}from"node:child_process";import E,{basename as ne,dirname as D,isAbsolute as re,join as ie,sep as O}from"node:path";import ae,{createHash as oe,createHmac as se,randomBytes as ce,randomUUID as le,timingSafeEqual as ue}from"node:crypto";import de from"node:net";import fe from"node:v8";import{open as pe,readFile as me,readdir as he,stat as ge}from"node:fs/promises";import{get as _e}from"node:https";import{WriteStream as ve}from"node:tty";import{createInterface as ye}from"node:readline";var be=Object.create,xe=Object.defineProperty,Se=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyNames,we=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,Ee=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),De=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ce(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Te.call(e,s)&&s!==n&&xe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Se(t,s))||r.enumerable});return e},Oe=(e,t,n)=>(n=e==null?{}:be(we(e)),De(t||!e||!e.__esModule?xe(n,`default`,{value:e,enumerable:!0}):n,e));let ke=!1;const Ae=()=>ke;function je(e){ke=e}function Me(e){return Ae()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ae()&&console.error(`[DEBUG] ${e}`,...t)}function Ne(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Pe=(e,t)=>k(t);function Fe(e,t){return Math.round(t-e)}function A(e,t){return Fe(t,e.monotonic())}const Ie={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=T(e);return()=>w(t)}};function Le(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function Re(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function ze(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function Be(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const Ve=e=>e.getTime()/1e3,He=e=>new Date(e*1e3),Ue=e=>Ve(new Date(e.now()));function We(e,t){return C.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!u(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Ge={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function Ke(e,t,n){let r=Ge[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function qe(e,t){return{...e.inherited,...t.envOverlay}}function Je(e){switch(e.reason){case`non-zero`:return`exited with code ${e.exitCode}`;case`signal`:return`killed by ${e.signal??`a signal`}`;case`timeout`:case`output-limit`:case`rate-limited`:case`pipe-error`:case`spawn-error`:return e.error??e.reason;default:return e.error===void 0?e.reason:`${e.reason}: ${e.error}`}}const Ye=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function Xe(e,t){if(e.reason===`output-limit`||e.reason===`pipe-error`)return``;let n=t.trim(),r=n.search(/[\r\n]/);if(r===-1)return Ye(n);let i=Math.max(n.lastIndexOf(`
|
|
3
3
|
`),n.lastIndexOf(`\r`))+1;return`${Ye(n.slice(0,r).trim())} … ${Ye(n.slice(i).trim())}`}function Ze(e,t=``){let n=Xe(e,e.stderr);return`${Je(e)}${t}${n===``?``:`: ${n}`}`}const Qe=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function $e(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 ${Math.round(n)}ms ago`}}function et(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function tt(e,t,n){let r=nt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function nt(e,t,n){if(e.scope.signal.aborted)return Qe(e.scope.signal);if(n?.aborted)return Qe(n);let r=Ke(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:$e(t,r.minIntervalMs,r.sinceLastMs)}const rt=`\$1 == "+" { live[\$2] = 1; next } \$1 == "-" { delete live[\$2]; next } END { for (g in live) groups = groups " -" g; if (groups != "") system("kill -TERM" groups " 2>/dev/null; sleep ${250/1e3}; kill -KILL" groups " 2>/dev/null") }`;function it(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function at(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),it(e,n))}const ot=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,st=e=>e===`cut`?`output cut at the ${gt}-byte bound, so the program holding it now fails its writes`:`output failed to read`,ct=`a launched program's pipe outlived its launch: `;function lt(e,t,n){let r=e.pipeEvent,i=new Map(r===null||r.answered?[]:r.counts),a=`${t}\0${n}`;i.set(a,(i.get(a)??0)+1),e.pipeEvent={text:`${ct}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${st(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${ct}${n} ${st(t)}`})}function ut(e,t){let n=e.pipeEvent;n===null||!Be(n,t)||(e.pipeEvent={...n,answered:!0})}function dt(e,t,n){let r=e.pipeEvent,i=r===null?`over`:ze(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:ot(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function ft(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[rt],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,A(n,r)),it(e,`did not start: ${We(i,void 0)}`),null}t?.onEnd(`lifeline`,A(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>it(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&it(e,null)}),i.once(`error`,t=>at(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>at(e,i,`exited ${n??t}`)),a.on(`error`,t=>at(e,i,`pipe failed: ${t.message}`)),et(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function pt(e,t){e.liveGroups.add(t),e.lifeline??=ft(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function mt(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function ht(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const gt=16*1024*1024,_t=`output exceeded ${gt} bytes`,vt=e=>`timed out after ${e/1e3} s`;function yt(e,t,n,r){let{stats:i}=e.scope,a=new b(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?lt(e,`read-error`,t):l.failed(n)}),n?.on(`data`,r=>{if(l===null){if(c+=r.length,i?.onDrainRead(t,r.length),c<=16777216)return;u=`cut`,n.destroy(),lt(e,`cut`,t);return}let d=Math.max(0,gt-s);o+=a.write(r.subarray(0,d)),s+=r.length,s>16777216&&l.full()}),{take:()=>{if(l===null)return``;l=null;let e=o+a.end();return o=``,e},drain:()=>{n===null||n.destroyed||n.readableEnded||bt(e,t,n,()=>u)}}}function bt(e,t,n,r){let{stats:i}=e.scope;if(e.scope.signal.aborted){n.destroy();return}n.once(`close`,()=>{e.drains.delete(n),i?.onDrainClose(t,r())}),n.unref(),e.drains.add(n),i?.onDrainOpen(t)}const xt=()=>`closed`;function St(e,t){e.on(`error`,()=>{}),e.end(t)}async function Ct(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category,t.signal);if(i!==null)return i;let a=r.monotonic();return n?.onStart(t.category),new Promise(i=>{let{spawner:o}=e,s;try{s=o.spawn(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,A(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)});return}let c=s.pid;c!==void 0&&pt(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>te(`output-limit`),failed:e=>{d??=e.message,te(`pipe-error`)}},p=yt(e,t.category,s.stdout,f),m=yt(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>te(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&mt(e,c),n?.onEnd(t.category,A(r,a)),s.off(`close`,ne),s.off(`error`,E),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&bt(e,t.category,u,xt),i())},w=e=>C(()=>i(e)),T=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),w({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},ee=()=>ne(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(ee);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let te=e=>{if(b!==null)return;if((s.exitCode!==null||s.signalCode!==null)&&c!==void 0&&o.groupGone(c)){b=e===`timeout`?null:e,r.defer(ee);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{T(t,`SIGKILL`),l.then(()=>r.defer(ee))}),T(t,`SIGTERM`))},E=e=>{w({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:We(e,t.cwd)})};s.on(`error`,E);let ne=(e,n)=>{if(b!==null){w({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:vt(t.timeoutMs??0)}:b===`output-limit`?{error:_t}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){w({ok:!0,...h(),exitCode:e});return}w({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,ne),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>te(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&St(u,t.stdinInput)})}function wt(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);try{let i=e.spawner.spawnSync(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:[`pipe`,`pipe`,`pipe`],encoding:`utf8`});n?.onEnd(t.category,A(r,a));let o=typeof i.stdout==`string`?i.stdout:``,s=typeof i.stderr==`string`?i.stderr:``,c=i.error?.code;if(i.error&&c!==`EPIPE`&&c!==`ECONNRESET`){let e=c===`ETIMEDOUT`?`timeout`:`spawn-error`;return{ok:!1,reason:e,stdout:o,stderr:s,exitCode:null,signal:i.signal??null,error:e===`timeout`?vt(t.timeoutMs??0):We(i.error,t.cwd)}}return i.status===0?{ok:!0,stdout:o,stderr:s,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:o,stderr:s,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,A(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)}}}function Tt(e,t){let{stats:n,clock:r}=e.scope,i=tt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=Et(e,t);return n?.onEnd(t.category,A(r,a)),o}function Et(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:qe(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:We(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const Dt=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Ot(e,t,n){let{stats:r,clock:i}=e.scope,a=tt(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.monotonic();r?.onStart(t.category);let s;try{s=e.spawner.spawn(`/bin/sh`,[`-c`,`out=$1 err=$2 status=$3; shift 3; read go || exit 0; "$@" >"$out" 2>"$err" </dev/null; echo "exit $?" >"$status.$$" && ln "$status.$$" "$status"; rm -f "$status.$$"`,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:qe(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,A(i,o)),{ok:!1,reason:`spawn-error`,error:We(e,t.cwd)}}r?.onEnd(t.category,A(i,o)),s.once(`error`,()=>{});let c=s.pid,l=s.stdin;return l.on(`error`,()=>{}),c===void 0?(l.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(s.unref(),l.unref(),{ok:!0,pid:c,release:()=>l.end(`go
|
|
4
|
-
`),withdraw:()=>l.end()})}function kt(e){let t;try{t=h(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function At(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Dt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{f(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{_(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function jt(e,t,n){return Nt(e,t,n).launcher}function Mt(e,t,n){let{launcher:r,state:i}=Nt(e,t,n);return{...r,launchSync:e=>wt(i,e)}}function Nt(e,t,n){let r={clock:t,launch:e=>et(i,Ct(i,e)),launchDetachedSync:e=>Tt(i,e),launchJobSync:(e,t)=>Ot(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>At(n,t,e,r,i),launcherWarnings:(e,t)=>dt(i,e,t),answeredPipeEvent:e=>ut(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&at(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:ot(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>Ve(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),ht(i)},{once:!0}),{launcher:r,state:i}}function Pt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Ft={spawn:(e,t,n)=>ee(e,t,n),spawnSync:(e,t,n)=>te(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Pt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},It=(e,t)=>jt(e,t,Ft),Lt=(e,t)=>Mt(e,t,Ft);function Rt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Ie;return{host:e,launcher:Lt({inherited:process.env},t),clock:t}}const zt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Bt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Vt(e){return zt.test(e)?e:Bt(e)}function Ht(e){return`${e.dir===void 0?``:`cd ${Vt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Vt(t)} `).join(``)}${[e.program,...e.args].map(Vt).join(` `)}`}const Ut=`cc-extra`;function j(e){return E.join(E.dirname(e),Ut,`src`,`bun-attach.js`)}function Wt(e){return E.join(E.dirname(e),`bun-graph.js`)}const Gt=`attach-preload.cjs`;function Kt(e){return E.join(E.dirname(e),Gt)}function qt(e,t){return Ht({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Jt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yt(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function M(e,t,n=Jt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?M(e,r):[[E.relative(e,r).split(E.sep).join(`/`),Yt(r,i)]]})}function Xt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Zt(e){return Xt(M(e,e))}const Qt=[`Cargo.toml`,`Cargo.lock`,`src`];function $t(e){return Xt(M(e,e,e=>Qt.includes(e)))}const en=e=>e.slice(0,7),tn=`1.219.
|
|
4
|
+
`),withdraw:()=>l.end()})}function kt(e){let t;try{t=h(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function At(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Dt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{f(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{_(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function jt(e,t,n){return Nt(e,t,n).launcher}function Mt(e,t,n){let{launcher:r,state:i}=Nt(e,t,n);return{...r,launchSync:e=>wt(i,e)}}function Nt(e,t,n){let r={clock:t,launch:e=>et(i,Ct(i,e)),launchDetachedSync:e=>Tt(i,e),launchJobSync:(e,t)=>Ot(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>At(n,t,e,r,i),launcherWarnings:(e,t)=>dt(i,e,t),answeredPipeEvent:e=>ut(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&at(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:ot(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>Ve(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),ht(i)},{once:!0}),{launcher:r,state:i}}function Pt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Ft={spawn:(e,t,n)=>ee(e,t,n),spawnSync:(e,t,n)=>te(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Pt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},It=(e,t)=>jt(e,t,Ft),Lt=(e,t)=>Mt(e,t,Ft);function Rt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Ie;return{host:e,launcher:Lt({inherited:process.env},t),clock:t}}const zt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Bt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Vt(e){return zt.test(e)?e:Bt(e)}function Ht(e){return`${e.dir===void 0?``:`cd ${Vt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Vt(t)} `).join(``)}${[e.program,...e.args].map(Vt).join(` `)}`}const Ut=`cc-extra`;function j(e){return E.join(E.dirname(e),Ut,`src`,`bun-attach.js`)}function Wt(e){return E.join(E.dirname(e),`bun-graph.js`)}const Gt=`attach-preload.cjs`;function Kt(e){return E.join(E.dirname(e),Gt)}function qt(e,t){return Ht({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Jt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yt(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function M(e,t,n=Jt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?M(e,r):[[E.relative(e,r).split(E.sep).join(`/`),Yt(r,i)]]})}function Xt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Zt(e){return Xt(M(e,e))}const Qt=[`Cargo.toml`,`Cargo.lock`,`src`];function $t(e){return Xt(M(e,e,e=>Qt.includes(e)))}const en=e=>e.slice(0,7),tn=`1.219.2`;function nn(e){let t=E.dirname(E.dirname(e));return s.existsSync(E.join(t,`src`))?t:null}function rn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:tn,digest:e}}function an(){return`e1de1cef31c03c1e34db2a54efb5e82ac6eb52fb8e38f61053cc958a3c2ee480`}function on(e){let t=JSON.parse(s.readFileSync(E.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${E.join(e,`package.json`)} has no version string`);return n}function sn(e,t){try{let n=nn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Zt(E.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:on(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function cn(e,t){let n=e[t];return n&&n.length>0?n:void 0}function ln(e){let t=cn(e.env,`XDG_STATE_HOME`)??E.join(e.home,`.local`,`state`);return E.join(t,`cc-candybar`)}function un(e){let t=cn(e.env,`XDG_CACHE_HOME`)??E.join(e.home,`.cache`);return E.join(t,`cc-candybar`)}function dn(e){return ln(e)}function fn(e){return e.env.CC_CANDYBAR_SOCKET||pn()}function pn(){let e=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function mn(e){s.mkdirSync(e,{recursive:!0,mode:448});let t=s.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.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 hn(e){mn(E.dirname(e));for(let t of[e,gn(e)])try{if(s.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function gn(e){return`${e}.lease`}function _n(e){return gn(fn(e))}function vn(e){return E.join(ln(e),`session-state.json`)}function yn(e){return E.join(ln(e),`settings-history.json`)}function bn(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function xn(e){return E.join(ln(e),`spawn.lock`)}function Sn(e){return E.join(ln(e),`spawn.cooldown`)}function Cn(e){return E.join(ln(e),`spawn.backoff`)}function wn(e){return E.join(ln(e),`watch-probe`)}function Tn(e){return E.join(ln(e),`daemon.log`)}function N(e){return{socket:fn(e),lease:_n(e),state:ln(e),registry:bn(e),log:Tn(e),sessionState:vn(e),settingsHistory:yn(e),watchProbe:wn(e),spawnBackoff:Cn(e)}}function En(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${E.join(cn(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:cn(t,`XDG_CONFIG_HOME`)??E.join(e.home,`.config`),dataHome:cn(t,`XDG_DATA_HOME`)??E.join(e.home,`.local`,`share`),dataDirs:(cn(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function Dn(e,t,n){let r=On(e);s.mkdirSync(E.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??s.statSync(r,{throwIfNoEntry:!1})?.mode;try{s.writeFileSync(i,t,a===void 0?{}:{mode:a}),s.renameSync(i,r)}catch(e){throw s.rmSync(i,{force:!0}),e}}function On(e){return kn(e).at(-1)}function kn(e){let{hops:t,stopped:n}=An(e);if(n!==null)throw n;return t}function An(e){let t=[e];try{for(let e=0;e<Mn;e++){let e=jn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${Mn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function jn(e){try{return s.lstatSync(e).isSymbolicLink()?E.resolve(s.realpathSync(E.dirname(e)),s.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Mn=40,Nn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Pn(e){return Object.fromEntries(Nn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Fn=[`native`,`node`,`frames`];function In(e,t){return{kind:e,bundle:t,source:null}}const Ln=[`ansi`,`frame`],Rn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function zn(e){let t=Jn(e.termCols),n=Jn(e.termRows),r=Yn(e.ssh),i=Kn(e.tmux),a=Gn(e.configEnv),o=Gn(e.claudeConfigDir),s=Wn(e.terminalEnv),c=ir(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&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Bn(e,t){return Rn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vn(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 Hn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Un(e){let t=Object.keys(Hn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Hn[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
5
5
|
`)}function Wn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Nn.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 Gn(e){return typeof e==`string`&&E.isAbsolute(e)?e:void 0}function Kn(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 qn=1e4;function Jn(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>qn?qn:t}function Yn(e){return typeof e==`boolean`?e:void 0}const Xn=new Set([...[],1]);function Zn(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}var Qn=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},$n=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function er(e){return tr(JSON.stringify(e))}function tr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function nr(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 Qn(`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 Qn(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function rr(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=t=>{if(!o){o=!0,c(),e.off(`data`,l),e.off(`error`,u),e.off(`close`,d);try{t()}catch{}}},c=r.after(n-r.now(),()=>{s(()=>{e.destroy(),a(new $n(`deadline`))})}),l=nr(e=>s(()=>i(e)),e=>s(()=>a(e))),u=e=>s(()=>a(e)),d=()=>s(()=>a(Error(`socket closed before response`)));e.on(`data`,l),e.on(`error`,u),e.on(`close`,d),e.write(er(t))})}function ir(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Gn(n);return Fn.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function ar(e,t,n,r){let i;try{i=await dr(fn(e.host),n.connectMs,e.clock)}catch(e){return ur(e)}return or(i,e.clock,t,n,r)}async function or(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await rr(e,{v:3,...o},a,t);return lr(o.kind,s,i)}catch(e){return ur(e)}finally{e.destroy()}}function sr(e,t){return typeof e==`string`?e:t}function cr(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function lr(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=sr(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:cr(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,phase:`deadline`,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 ur(e){if(e instanceof Qn||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 e instanceof $n?{kind:`busy`,phase:e.phase,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 dr(e,t,n){return new Promise((r,i)=>{let a=de.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new $n(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function fr(e){if(e.kind===`busy`)return`daemon busy (${e.message})`;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}`}}function pr(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function mr(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-60-n.monoMs)}const hr={connectMs:50,budgetMs:150},gr={connectMs:50,budgetMs:350};function _r(e){let t=e.output;return typeof t==`string`?t:void 0}function vr(e){return lr(`render`,e,_r)}function yr(e,t,n,r,i,a=hr){return ar(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,_r)}function br(e,t,n){return ar(e,()=>({kind:`pane-session`,socket:t,pane:n}),gr,e=>`paneSession`in e?e.paneSession:void 0)}function xr(e,t,n){return ar(e,()=>({kind:`click`,verb:t,value:n}),gr,_r)}const Sr=5e3;async function Cr(e){let t=[];for(let n of e){let e=await 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(`
|
|
6
6
|
`)}const wr=`/usr/bin/footprint`;function Tr(e,t,n){return t===`darwin`?[kr(e,wr,[`-p`,String(n)]),kr(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[Ar(`/proc/self/smaps_rollup`),Ar(`/proc/self/status`)]:[]}function Er(e,t,n){return t===`darwin`?Dr(n,t=>e.launch({bin:wr,args:t,timeoutMs:Sr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Dr(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 ${Ze(r)}`};let i=Or(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 Or(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function kr(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:Sr,category:`limits.memory-report`});return r.ok?r.stdout.trim().length>0?{kind:`text`,text:r.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:Ze(r)}}}}function Ar(e){return{name:e,read:async()=>{try{let t=s.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}}}}}const jr=`CC_CANDYBAR_RSS_LIMIT_MB`;function Mr(e){let t=e[jr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${jr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Nr(e){return Mr(e)*2}const Pr=1024*1024,Fr=e=>Math.round(e/Pr);function Ir(e){return Mr(e)*Pr}const Lr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Rr(e,t){return e>t}function zr(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}}const Br=.75;function Vr(e,t){return e>t*Br}function Hr(e,t,n){let{prefix:r,suffix:i}=Lr[t];return E.join(e,`${r}${n}${i}`)}function Ur(e){for(let t of Object.keys(Lr)){let{prefix:n,suffix:r}=Lr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Wr(e){let t=e.limitBytes??1024*Pr,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null,o=!1,s;function c(){return a??=l().finally(()=>{a=null}),a}async function l(){if(r)return!0;let{rss:a,heapTotal:s}=e.memoryBytes(),c=zr(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${qr(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Gr(c)} > limit ${Fr(t)} MB (rss ${Fr(a)} MB, v8 heap ${Fr(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Jr(e.log,`memory report`,async()=>{let t=Hr(e.snapshotDir,`memoryReport`,u),n=await e.captureMemoryReport();o||(e.writeMemoryReport(t,n),e.log(`info`,`memory report written: ${t}`))}),o?(e.log(`info`,`daemon closed during the breach: no snapshot, no exit`),!1):(await Jr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Hr(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Jr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Yr(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Jr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Vr(i.charge.bytes,t)?`${Gr(i.charge)} approaching limit ${Fr(t)} MB (v8 heap ${Fr(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Yr(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function f(t=6e4){let n=async()=>{try{if(await c())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}o||(s=e.clock.after(t,()=>void n(),{unref:!0}))};n()}function p(){o=!0,s?.()}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function Gr(e){return e.kind===`charged`?`${e.measure} ${Fr(e.bytes)} MB`:`rss ${Fr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Fr(e.gap)} MB gap`} (standing in: ${e.unread})`}function Kr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function qr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Fr(e.gap)}MB`:``;return`measure=${Kr(e)} charge=${Fr(e.bytes)}MB rss=${Fr(t)}MB heap=${Fr(n)}MB limit=${Fr(r)}MB${i}`}async function Jr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Yr(e){let t=new Map;for(let n of e){let e=E.basename(n),r=Ur(e);if(r===null)continue;let{prefix:i,suffix:a}=Lr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Lr);return[...t].sort(([e],[t])=>Rr(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function Xr(e,t,n,r={}){let i=n.snapshotDir;return{clock:n.clock,pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Er(n.launcher,process.platform,process.pid),captureMemoryReport:()=>Cr(Tr(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>s.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>fe.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=s.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Ur(e)!==null).map(e=>E.join(i,e))},removeFile:e=>s.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Zr(e,n={}){let{host:r,clock:i}=e;if(pi(r)!==null)return;let a=n.spawn??(()=>hi(e)),o=ui(r,i);if(o.kind===`contended`){let e=$r(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Qr(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Qr(r,i,a);return}try{Qr(r,i,a)}finally{fi()}}function Qr(e,t,n){oi(e,t)&&ei(n)}function $r(e,t){try{let n=s.statSync(xn(e));return t.now()-n.mtimeMs}catch{return null}}function ei(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
7
7
|
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function ti(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ni(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function ri(e){try{let t=s.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function ii(e,n){try{s.mkdirSync(E.dirname(e),{recursive:!0}),s.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function ai(e){try{s.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function oi(e,n){let r=Sn(e),i=Cn(e),a=ri(i),o=ti(si(r,n),ni(a));return o.kind===`deny`?!1:(o.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${o.futureMs}ms in the future — ignoring and spawning\n`),ci(r,n),ii(i,Math.min(a+1,5)),!0)}function si(e,t){try{return t.now()-s.statSync(e).mtimeMs}catch{return null}}function ci(e,n){try{s.mkdirSync(E.dirname(e),{recursive:!0}),s.writeFileSync(e,`${t.pid} ${n.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let li=null;function ui(e,n){let r=xn(e);for(let e=0;e<2;e++){try{let e=s.openSync(r,`wx`,384);try{s.writeSync(e,JSON.stringify({pid:t.pid,ts:n.now()}))}catch{}return li={fd:e,path:r},{kind:`held`}}catch(e){let t=e.code;if(t!==`EEXIST`)return{kind:`error`,reason:`openSync(${r}): ${t??e.message}`}}if(!di(r,n))return{kind:`contended`};try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function di(e,t){try{let n=s.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function fi(){if(!li)return;let{fd:e,path:t}=li;li=null;try{s.closeSync(e)}catch{}try{s.unlinkSync(t)}catch{}}function pi(e){try{return s.mkdirSync(dn(e),{recursive:!0}),null}catch(t){return`mkdir ${dn(e)}: ${t.message}`}}function mi(e,t){return[`--max-old-space-size=${Nr(t)}`,e,`daemon`]}function hi({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:mi(i,e.env),category:`daemon-spawn`}).ok:!1}const gi=`closed`,_i=`open`,vi=`🍫`;function yi(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function bi(e,t,n,r){let i=yi(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function xi(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Si(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function Ci(e,...t){return`{{ and ${[e,...t].map(wi).join(` `)} }}`}function wi(e){return`(eq .${e.variable} "${xi(e.member)}")`}function Ti(e,t,n){return`{{ ${Ei(e,Di(t),Di(n))} }}`}function Ei(e,t,n){return`action "${e}" ${t} ${n}`}function Di(e){return`"${xi(e)}"`}function Oi(e,t){return{kind:`state`,key:e,default:t}}function ki(e,t){return{set:e,cycle:[gi,t]}}function Ai(e){if(!(`set`in e&&`cycle`in e))return;let[t,n,...r]=e.cycle;return t===`closed`&&n!==void 0&&r.length===0?{key:e.set,member:n}:void 0}const ji=`groups.`,Mi=`menus.`,Ni=`menupages.`,Pi=`edit.`,P=`candybar.`,Fi=[ji,Mi,Ni,Pi,P];function Ii(e){return Fi.some(t=>e.startsWith(t))}const Li=`${P}menu`,Ri=_i,zi={variable:Li,key:Li,member:Ri},Bi=`${P}diagnostics`,Vi=`cc-candybar`,Hi=`CCCandybarURLHandler`,Ui=`dispatch`,Wi=`set-state`,Gi=`step-state`,Ki=`copy`,qi=`open-vscode`,Ji=`toolbar-toggle`,Yi=`load-config`,Xi=`set-config`,Zi=`step-config`,Qi=`save`,$i=`save-preset`,ea=`save-theme-default`,ta=`delete-preset`,na=`reset-config`,ra=`apply-layout-op`,ia=`undo`,aa=`redo`,oa=`back`,sa=`rewind`,ca=`apply-update`,la=`doctor-run`,ua=`doctor-fix`,da=`doctor-mark`,fa=`doctor-probe`,pa=`slash`,ma=`repo-config`,ha=`copy-diagnostic`,ga=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,_a=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function va(e,t){if(e===Bi)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!Ii(e))return n;let r=_a(_a(e,Ni),Mi);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}function ya(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const ba={[Wi]:([,...e])=>e.flatMap((t,n)=>n%2==0?[va(t,e[n+1])]:[]),[Gi]:([,e,t])=>[ga(e,t)],[Ki]:([e])=>[`copy ${ya(e)}`],[qi]:([e])=>[`open ${e} in vs code`],[Ji]:()=>[`toggle the toolbar`],[Yi]:([,e])=>[`load config ${e}`],[Xi]:([,e,t])=>[`save ${e} as ${t}`],[Zi]:([,e,t])=>[`save ${ga(e,t)}`],[Qi]:()=>[`save settings`],[$i]:()=>[`save as a new preset`],[ea]:()=>[`save this look for the theme`],[ta]:([,e])=>[`delete preset ${e}`],[na]:([,...e])=>e.map(e=>`reset ${e}`),[ra]:([,e,t])=>[`edit ${t} in ${e}`],[ia]:()=>[`undo`],[aa]:()=>[`redo`],[oa]:()=>[`go back`],[sa]:()=>[`cancel edits`],[ca]:()=>[`update cc-candybar`],[la]:()=>[`run doctor`],[ua]:([,e])=>[`fix ${e}`],[da]:([,e,t])=>[`mark ${e} ${t}`],[pa]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[ma]:([,e,t])=>[`mark config in ${e} ${t}`],[ha]:()=>[`copy diagnostic`]},xa=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function Sa(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>ba[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function Ca(e){return e.map(encodeURIComponent).join(`/`)}function wa(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function eee(e){return decodeURIComponent(e.split(`/`,1)[0])}function Ta(e,t=Sa(e)){let n=e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Ca(e.args)}`)}`);return`${Vi}://${Ui}/${[`does=${xa(t)}`,...n].join(`&`)}`}function Ea(e){return new r(e).getAll(`e`).map(Aa)}const Da=new Set([Wi,na]);function Oa(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&ka(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function ka(e,t){if(e.verb!==t.verb||!Da.has(e.verb))return;let[n,r]=[Aa(e.value),Aa(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function Aa(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function ja(e){let t=`${Vi}://`;if(!e.startsWith(t))return{ok:!1,problem:`expected a ${t} link, got: ${e}`};let n=e.slice(t.length),r=n.indexOf(`/`);if(r===-1)return{ok:!0,verb:Ki,value:n};let i=n.slice(0,r);try{return{ok:!0,verb:decodeURIComponent(i),value:n.slice(r+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${i}`}}}var Ma=Ee(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),Na=Ee(((e,t)=>{let n=Ma();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),Pa=Ee(((e,t)=>{let n=Na(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),te[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
|
|
@@ -51,23 +51,23 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
51
51
|
`).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+z(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*am(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 om=Object.freeze({name:`join`});function sm(e,t,n,r){let i=e.join(t,n,r);return{render:e=>W.anchorLines([[...ip(i,e)]],om)[0]}}function cm(e){return{render:t=>W.anchorLines([[...ip(e,t)]],e)[0]}}var lm=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*ip(sm(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*ip(cm(r),n);let i=e+1<t.length?t[e+1]:null;yield*ip(sm(this.joiner,r,i,{index:e+1}),n)}yield W.line()}measure(e){let t=0;for(let n of ip(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const xee=[`seam`,`lead`,`tail`];function*um(e){yield e,`mix`in e&&(yield*um(e.mix[0]),yield*um(e.mix[1]))}const dm=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,See=(e,t,n,r)=>{let i=dm(e);return i[Math.floor(parseInt(zp(`${t}:${n}:${r}`),16)/2**32*i.length)]},Cee=e=>z(dm(e)[0]??``);function fm(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([fm(e,t,n),fm(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const pm=(e,t,n)=>e===`ground`?e:fm(e,t,n),mm={seam:void 0,lead:`left`,tail:`right`},wee={seam:`seam`,lead:`caps`,tail:`caps`};function hm(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=dm(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>z(t)!==Cee(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(Gf)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:pm(e.fg,mm[n],r),bg:pm(e.bg,mm[n],r)})}function gm(e,t,n,r){let i=e,a=wee[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 _m=(e,t)=>(n,r)=>hm(n,e,t,r),Tee=(e,t)=>(n,r)=>{if(!(`cap`in n))return hm(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)}`)};function vm(e){let t=t=>Object.freeze({seam:gm(e,t,`seam`,Tee(t,`seam`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function ym(e){let t=t=>Object.freeze({lead:gm(e,t,`lead`,_m(t,`lead`)),tail:gm(e,t,`tail`,_m(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function bm(e,t){return{seam:e.seam.flatMap(e=>`cap`in e?t[e.cap]:[e]),lead:t.lead,tail:t.tail}}const xm=(e,t)=>new Set([e.fg,e.bg].flatMap(e=>e===`ground`?[]:[...um(e)].flatMap(e=>`edge`in e&&e.edge===t?[e.part]:[]))),Sm=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...um(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function Cm(e){let t=t=>e[t].map(e=>({cell:e,parts:{left:xm(e,`left`),right:xm(e,`right`)}}));return{shape:e,reads:{seam:{left:Sm(e.seam,`left`),right:Sm(e.seam,`right`)},lead:Sm(e.lead,`right`),tail:Sm(e.tail,`left`)},cells:{seam:t(`seam`),lead:t(`lead`),tail:t(`tail`)}}}function wm(e){return e!==void 0&&!e.isDefault?e:void 0}function Tm(e){return e.flattenAlpha(yl)}function Em(e,t){if(e.isDefault||t.isDefault)return!0;let[n,r]=[e.fixedValue,t.fixedValue];return n!==void 0&&r!==void 0?ju.fromRgba(n).deltaE(ju.fromRgba(r))>=.04:e.number===void 0?e.name!==t.name:e.number!==t.number}const Dm=.001;function*Om(e){for(let t=1;t*Dm<=1;t++)for(let n of[e.l+t*Dm,e.l-t*Dm])n>=0&&n<=1&&(yield new ju(n,e.c,e.h))}function km(e,t,n){if(e===void 0||t===void 0)return e;let r=(e,n)=>new U({color:e,bgcolor:t}).drawnColors(n),{color:i,bgcolor:a}=r(e,n);if(Em(i,a))return e;let o=r(e).color,s=i.fixedValue===void 0?V.STANDARD:V.TRUECOLOR;for(let e of Om(ju.fromRgba(o.getTruecolor()))){let t=r(H.fromRgba(e.toRgba()).downgrade(s),n).color;if(Em(t,a))return t}throw Error(`no colour on the lightness ray of ${e.name} stands off ${t.name} at depth ${V[n]}`)}function Am(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=wm(n?.bgcolor);return r&&Tm(r)}if(`role`in e)return qf(n,e.role).color;let[r,i,a]=e.mix,o=Am(r,t,n),s=Am(i,t,n);return o&&s&&H.blend(o,s,a)}function jm(e,t,n){if(e.fg===`ground`)return new U({color:e.bg===`ground`?void 0:Am(e.bg,t,n),reverse:!0});let r=e.bg===`ground`?void 0:Am(e.bg,t,n);return new U({color:km(Am(e.fg,t,n),r,n.colorSystem??V.TRUECOLOR),bgcolor:r})}var Mm=class e{cell;parts;neighbours;edges;options;reads;follows;style;constructor(e,t,n,r,i){this.cell=e,this.parts=t,this.neighbours=n,this.edges=r,this.options=i;let a=e=>{if(t[e].size===0)return null;let[i,a]=[n[e],r[e]];if(i===null||a===void 0)throw Error(`a join cell paints with its ${e} neighbour's edge, and the join has no ${e} neighbour`);return{owner:i,edge:a}};this.reads={left:a(`left`),right:a(`right`)},this.follows=this.reads.left!==null||this.reads.right!==null,this.style=jm(e,r,i)}rederived(t,n,r){let i=e=>t[e]?.color!==void 0&&this.parts[e].has(`fg`)||t[e]?.bgcolor!==void 0&&this.parts[e].has(`bg`);if(!i(`left`)&&!i(`right`))return;let a=(e,t)=>t===void 0?e:new U({color:t.color??e?.color,bgcolor:t.bgcolor??e?.bgcolor}),o={left:a(this.edges.left,t.left),right:a(this.edges.right,t.right)},s=new e(this.cell,this.parts,this.neighbours,o,{...this.options,colorSystem:r}),c=e=>({...e,owner:e.owner===this?s:e.owner,inner:e.inner&&c(e.inner)});return{colors:s.style,style:n.withAnchor(n.anchor&&c(n.anchor))}}};function Nm(e){for(let t=e;t;t=t.inner)if(t.owner instanceof Mm)return t.owner}const Pm=e=>xee.flatMap(t=>e[t].flatMap(dm)).join(``);var Fm=class{seam;caps;_forms;constructor(e,t){this.seam=vm(e),this.caps=ym(t),this._forms={glyph:Cm(bm(this.seam.glyph,this.caps.glyph)),ascii:Cm(bm(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{cells:a,reads:o}=Kf(i,r.glyph,r.ascii,e=>Pm(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=wm(s.left?.bgcolor),l=wm(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=>a[e].map(({cell:t,parts:r},a)=>{let o=new Mm(t,r,m,s,i);return new W(See(t,e,n,a),o.style.withAnchor({owner:o,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*h(f?`lead`:`tail`));return}yield*h(`seam`)}}}};const Im={edge:`left`,part:`bg`},Lm={edge:`right`,part:`bg`},Rm={edge:`left`,part:`fg`},zm={mix:[Im,Lm,1/2]},Bm=`ground`,Vm={cap:`lead`},Hm={cap:`tail`},Um=(e,t)=>({glyph:e,ascii:t}),Wm={glyph:``,ascii:`>`},Gm={glyph:``,ascii:`/`},Km={glyph:``,ascii:`\\`},qm={glyph:``,ascii:`}`},Jm={glyph:``,ascii:`#`},Ym={glyph:``,ascii:`]`},Xm={glyph:``,ascii:`)`},Zm=e=>({seam:[{glyph:e,fg:Im,bg:Lm}]}),Qm=e=>Um(Zm(e.glyph),Zm(e.ascii));function $m(e){let t=e=>({mix:[Im,Lm,e]});return{seam:[{glyph:e,fg:Im,bg:t(1/3)},{glyph:e,fg:t(1/3),bg:t(2/3)},{glyph:e,fg:t(2/3),bg:Lm}]}}const eh=e=>({seam:[Hm,...e,Vm]}),th=(e,t)=>({seam:[{glyph:e,fg:t,bg:zm}]}),nh=e=>th({oneOf:e},Im),rh={seam:[{glyph:` | `,fg:{role:`strip.separator`},bg:Bm}]},ih={glyph:` `,fg:Rm,bg:Bm},ah=e=>({glyph:e,fg:{role:`strip.rail`},bg:Bm}),oh=Object.freeze({powerline:vm(Qm(Wm)),prism:vm(Um($m(Wm.glyph),$m(Wm.ascii))),slant:vm(Qm(Gm)),backslant:vm(Qm(Km)),flame:vm(Qm(qm)),pixel:vm(Qm(Jm)),ice:vm(Qm(Ym)),bubble:vm(Qm(Xm)),capsule:vm(Um(eh([ih]),eh([ih]))),wrapper:vm(Um(eh([]),eh([]))),metro:vm(Um(eh([ah(`──`)]),eh([ah(`--`)]))),stitch:vm(Um(th(`┊`,Rm),th(`:`,Rm))),torn:vm(Um(nh([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),nh([`/\\`,`\\/`]))),plain:vm(Um(rh,rh))}),sh=e=>Um({lead:[{glyph:e.glyph,fg:Bm,bg:Lm}],tail:[{glyph:e.glyph,fg:Im,bg:Bm}]},{lead:[],tail:[{glyph:e.ascii,fg:Im,bg:Bm}]}),ch=(e,t)=>({lead:[{glyph:e,fg:Lm,bg:Bm}],tail:[{glyph:t,fg:Im,bg:Bm}]}),lh={lead:[],tail:[]},uh=Object.freeze({powerline:ym(sh(Wm)),slant:ym(sh(Gm)),backslant:ym(sh(Km)),flame:ym(sh(qm)),pixel:ym(sh(Jm)),ice:ym(sh(Ym)),bubble:ym(sh(Xm)),capsule:ym(Um(ch(``,``),ch(`(`,`)`))),wrapper:ym(Um(ch(``,``),ch(`<`,`>`))),flat:ym(Um(lh,lh))}),dh=Object.freeze({powerline:new Fm(oh.powerline,uh.powerline),prism:new Fm(oh.prism,uh.powerline),slant:new Fm(oh.slant,uh.slant),backslant:new Fm(oh.backslant,uh.backslant),flame:new Fm(oh.flame,uh.flame),pixel:new Fm(oh.pixel,uh.pixel),ice:new Fm(oh.ice,uh.ice),bubble:new Fm(oh.bubble,uh.bubble),capsule:new Fm(oh.capsule,uh.capsule),wrapper:new Fm(oh.wrapper,uh.wrapper),metro:new Fm(oh.metro,uh.capsule),stitch:new Fm(oh.stitch,uh.flat),torn:new Fm(oh.torn,uh.flat),plain:new Fm(oh.plain,uh.flat)});function fh(e,t){let n=t.reducedMotion?e.style?.reduced():e.style;return n===e.style?e:new W(e.text,n,e.control)}function ph(e,t){if(e.isControl)return``;let{text:n,style:r}=fh(e,t);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:`${Hp(o)}${a}]8;;\\`}function mh(e,t){let n=[];for(let r of e)n.push(ph(r,t));return n.join(``)}function hh(e){return e.end=``,e.plain=e.plain.replaceAll(`
|
|
52
52
|
`,` `),e.expandTabs()}const gh={lastChange:-1/0,nextChange:1/0};var _h=class{renderable;effect;t;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.t=ff(`Effected`,n.t),this.key=n.key,this.theme=n.theme}render(e){return this.moved(e).segments}moved(e){let t=ip(this.renderable,e);if(e.colorSystem===null)return{segments:t,hold:gh};let n=e.colorSystem??V.TRUECOLOR,r=xh(t,n,this.theme),i=wh(r),a=mp(this.effect(Dh(r,()=>i,n,this.theme)),this.t,e);return{segments:this._recolored(i,a.value,n),hold:hp(a,this.t)}}*_recolored(e,t,n){let r=e.map(({look:e,glyphs:n})=>{if(e===void 0)return;let r=Nm(e.style.anchor);if(r?.follows===!0)return{joined:r};let i={fg:e.pair.fg,bg:e.pair.bg,attributes:e.attributes},{terminal:a,reverse:o}=e.pair;return{painted:n.map(({cell:e})=>e===void 0?i:Ph(t(i,{...e,seed:yh(this.key,e.row,e.col),terminal:a,reverse:o})))}}),i=Th(e,r);for(let[a,{segment:o,look:s,glyphs:c}]of e.entries()){let e=r[a];s===void 0||e===void 0?yield o:`joined`in e?yield this._rejoined(o,s,e.joined,c,i,t,n):yield*this._repainted(o,s,c,e.painted,n)}}*_repainted(e,t,n,r,i){let{style:a,wire:o,slots:s,pair:c,attributes:l}=t,u=[];for(let[e,{glyph:t}]of n.entries()){let n=r[e],a=kh(n,c.reverse),l=u[u.length-1],d=l!==void 0&&zh(l.colors,a)?l.drawn:this.respec(o,s,a,i);l!==void 0&&jh(l.drawn,d)&&Lh(l.attributes,n.attributes)?(l.text+=t,l.cells+=z(t),l.colors=a):u.push({text:t,cells:z(t),colors:a,attributes:n.attributes,drawn:d})}if(u.every(e=>jh(e.drawn,o)&&Lh(e.attributes,l))){yield e;return}let d=0;for(let e of u){let t=a.shiftedBy(d),n=Lh(e.attributes,l)?t:t.withAttributes(Ih(e.attributes)),r=jh(e.drawn,o)?n:n.add(U.fromColor(e.drawn.color,e.drawn.bgcolor));yield new W(e.text,r),d+=e.cells}}_rejoined(e,t,n,r,i,a,o){let s=r.flatMap(({cell:e})=>e===void 0?[]:[e]),[c]=s;if(c===void 0)return e;let{theme:l}=this,u=new Set,d=(e,t)=>{if(!e?.isDefault)return e;let n=H.fromRgba(e.getTruecolor(l,t));return u.add(n),n},f=(e,t)=>{let n=Ah(e,t,o,l);return n.fg===void 0&&n.bg===void 0?void 0:{color:d(n.fg,!0),bgcolor:d(n.bg,!1)}},p=e=>{let t=e.drawnColors(o),n={fg:(t.color??bh).getTruecolor(l,!0),bg:(t.bgcolor??bh).getTruecolor(l,!1)},r={fg:t.color?.isDefault??!0,bg:t.bgcolor?.isDefault??!0};return f(n,Ph(a({...n,attributes:Ih(e)},{...c,seed:yh(this.key,c.row,c.col),terminal:r,reverse:!1})))},m=e=>{let t=n.reads[e];if(t===null)return;let r=i(s,e,t.owner);return r===void 0?p(t.edge):f(r.look.slots,kh(r.moved,r.look.pair.reverse))},h=n.rederived({left:m(`left`),right:m(`right`)},t.style,o);if(h===void 0)return e;let{colors:g,style:_}=h,v=n.style,y=g.drawnColors(o),{wire:b,slots:x}=t,S=this.respec(b,x,{fg:g.color?.getTruecolor(l,!0)??x.fg,bg:g.bgcolor?.getTruecolor(l,!1)??x.bg},o),C=(e,t,n,r,i)=>{if(Rh(e,t))return n;if(e===void 0)throw Error(`a seam cell resolved to ${t?.name??`nothing`} when drawn and to nothing after an effect moved its neighbours`);return u.has(e)?i:r},w={color:C(g.color,v.color,b.color,y.color,S.color),bgcolor:C(g.bgcolor,v.bgcolor,b.bgcolor,y.bgcolor,S.bgcolor)};return new W(e.text,jh(w,b)?_:_.add(U.fromColor(w.color,w.bgcolor)))}measure(e){return dp.get(e,this.renderable)}respec(e,t,n,r){let i=Ah(t,n,r,this.theme);return{color:i.fg??e.color,bgcolor:i.bg??e.bgcolor}}},vh=class e{renderable;effect;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.key=n.key,this.theme=n.theme}at(e){return new _h(this.renderable,this.effect,{t:e,key:this.key,theme:this.theme})}nextChange(e){return e}lastChange(e){return e}reduced(){let{effect:t}=this;return new e(this.renderable,e=>t(e).reduced(),this)}render(e){let{segments:t,hold:n}=this.at(vp(e)).moved(e);return _p(t,n)}measure(e){return dp.get(e,this.renderable)}static shows(e,t,n,r){let i=kh(e,e.reverse),a=Ah(i,kh(t,e.reverse),n,r);return kh({fg:a.fg?.getTruecolor(r,!0)??i.fg,bg:a.bg?.getTruecolor(r,!1)??i.bg},e.reverse)}};function yh(e,t,n){return Number.parseInt(zp(`${e}:${t}:${n}`),16)/4294967296}const bh=H.default();function xh(e,t,n){return[...e].map(e=>{if(e.isControl)return{segment:e,look:void 0};let r=e.style??U.null(),i=r.drawnColors(t),a={fg:(i.color??bh).getTruecolor(n,!0),bg:(i.bgcolor??bh).getTruecolor(n,!1)},o=r.reverse===!0,s=kh({fg:i.color?.isDefault??!0,bg:i.bgcolor?.isDefault??!0},o);return{segment:e,look:{style:r,wire:i,slots:a,pair:{...kh(a,o),terminal:s,reverse:o},attributes:Ih(r),seam:Sf(r.anchor,om)}}})}function Sh(e){let t=0,n=0;return e.map(e=>{if(e.isControl)return[];let r=e.style?.anchor,i=0;return[...cl(e.text)].map(e=>{let a=e===`
|
|
53
53
|
`?void 0:{row:t,col:n,anchor:r&&xf(r,i)},o=z(e);return[t,n]=e===`
|
|
54
|
-
`?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Ch(e){return e.trim()!==``}function wh(e){let t=Sh(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Th(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&Sf(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&Sf(t.anchor,i))return t}}}function Eh(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Dh(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||Eh(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Ch(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Ch(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Oh(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>G.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function kh(e,t){return t?{fg:e.bg,bg:e.fg}:e}function Ah(e,t,n,r){let i=t.bg.compositeOver(yl),a=t.fg.compositeOver(i);return{fg:H.matchMove(e.fg,a,n,r,!0),bg:H.matchMove(e.bg,i,n,r,!1)}}function jh(e,t){return Mh(e.color,t.color,!0)&&Mh(e.bgcolor,t.bgcolor,!1)}function Mh(e,t,n){return e===t||Nh(e,n)===Nh(t,n)}function Nh(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function Ph(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const Fh=wf.filter(e=>e!==`reverse`);function Ih(e){return Object.fromEntries(Fh.map(t=>[t,e[t]]))}function Lh(e,t){return e===t||Fh.every(n=>e[n]===t[n])}function Rh(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function zh(e,t){return Bh(e.fg,t.fg)&&Bh(e.bg,t.bg)}function Bh(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const Vh=(()=>{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]})(),Hh=e=>e*e*e*(e*(e*6-15)+10),Uh=(e,t,n)=>e+n*(t-e);function Wh(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 Gh(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=Hh(e),u=Hh(t),d=Hh(n),f=Vh[o]+s,p=Vh[f]+c,m=Vh[f+1]+c,h=Vh[o+1]+s,g=Vh[h]+c,_=Vh[h+1]+c;return Uh(Uh(Uh(Wh(Vh[p],e,t,n),Wh(Vh[g],e-1,t,n),l),Uh(Wh(Vh[m],e,t-1,n),Wh(Vh[_],e-1,t-1,n),l),u),Uh(Uh(Wh(Vh[p+1],e,t,n-1),Wh(Vh[g+1],e-1,t,n-1),l),Uh(Wh(Vh[m+1],e,t-1,n-1),Wh(Vh[_+1],e-1,t-1,n-1),l),u),d)}function Kh(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*Gh(e*r,t*r,n*r),o+=a,a/=2}return i/o}function qh(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function Jh(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const Yh=Array.from({length:48},(e,t)=>(t+1)/48);function Xh(e,t){return Math.min(xl(e.fg,e.bg),4.5)-(t===V.TRUECOLOR?.01:0)}const Zh=[`fg`,`bg`];function Qh({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=>Zh.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=>ju.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=Zh.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=Xh(r,t),c=(t,n)=>ag(i,r[t],(t===a?e:o)*n);return Yh.every(e=>{let i=vh.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return xl(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 $h(e,t){let n=new qc;return rg(ng(e,r=>{let i=t??r.colors,a=[eg(r),`|`,...i].join(` `);return n.get(r.theme,()=>new Kc).get(a,()=>Qh(r,i,e.touch))}))}function eg({depth:e,pairs:t}){return[e,...t.map(tg)].join(` `)}function tg({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function ng(e,t){return n=>{let r=t(n);return G.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(ug(i(n))*48)/48,o=(t,n)=>ag(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function rg(e){return t=>ig(t.depth)?G.constant(e=>e):e(t)}function ig(e){switch(e){case V.DEFAULT:case V.STANDARD:case V.WINDOWS:return!0;case V.EIGHT_BIT:case V.TRUECOLOR:return!1}}function ag(e,t,n){return n===0?t:e(t,n)}function og(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}`)}function sg(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const cg={shimmer:{seconds:109,ease:sf.linear,swing:.9},pulse:{seconds:43,ease:sf.linear,swing:.85},sparkle:{seconds:139,ease:sf.linear,swing:.95},wheel:{seconds:907,ease:sf.linear,swing:1},fade:{seconds:20,ease:sf[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:sf[`ease-in-out`],swing:1}},lg={sun:new B(255,228,176),firefly:new B(222,245,140)},ug=e=>Math.min(1,Math.max(0,e));function dg(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 ju((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function fg(e){let t=ju.fromRgba(e);return(e,n)=>{let r=ju.fromRgba(e);return dg(r,new ju(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const pg=(e,t)=>t*e[e.length-1][0];function mg(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 hg(e,t,n){let r=pg(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=mg(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const gg=[[.24,1],[.6,0]];function _g(e,t,n){og(e),sg(`pulse`,n);let r=.9+.2*qh(n,3.1),i=t=>.1*Gh(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:fg(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*Jh(-.5,.5,Gh(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 vg=e=>Math.abs(e)>=1?0:(1-e*e)**3;function yg(e,t,n,r){og(e),sg(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>Jh(-.4,.4,Gh(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(qh(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*qh(e,8.5+r))),p=i*u/80*(c+l*qh(e,5.5+r)),m=ug((n-(e+s*qh(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*Gh(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(-((Gh(e,t,n)/.8)**2));return{touch:fg(n),field:(n,i)=>{let[a,o]=Eg(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*vg((i.col-a-n)/t));let c=i.row+r,l=.8*Gh(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 bg(e,t,n){og(e),sg(`sparkle`,n);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*Gh(e*1.7+.2,.3+t*2.9,.5+n),l=i+qh(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=qh(u,s+1)<.15?0:1,f=.5+.5*qh(u,s+2),p=qh(u,s+3)*(1-pg(gg,f)),m=l/r-u-p;return{x:a+c*8+5*(2*qh(u,s+4)-1)+5*f*(2*qh(u,s+5)-1)*hg(gg,m,f)+1.5*Gh(s,.1,i*.035),y:o+t*3+.6*Gh(s,2.2,i*.035),glow:d*mg(gg,m,f)}};return{touch:fg(t),field:(t,n)=>{let r=n.cells(),[s,c]=Eg(r.map(e=>e.col)),[l,u]=Eg(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*vg(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function xg(e,t){return n=>{let r=ju.fromRgba(n.theme.backgroundColor);return G.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-ug(a(n)));if(i===0)return e;let o=dg(ju.fromRgba(e.bg),r,i);return{...e,fg:dg(ju.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Sg(e){return t=>ug(.5+1.1*Kh(t.col*.09+1.4*Gh(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var Cg=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return G.done(this.schedule,e)}};function wg(e,t){let n=G.of({...G.sequence(G.continuous(()=>void 0),e,G.constant(void 0)),reduced:()=>G.cut(void 0,void 0)}),r=new Cg(i=>{let a=t(i);return G.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>G.cut(a.at(0),a.at(e))})},n);return r}function Tg(e,t){return(n,r)=>{let[i,a]=Eg(r.map(t)),o=(a>i?.55:0)*e.seconds,s=bf.once(0,e.seconds-o);return e=>{let r=a>i?ug((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function Eg(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 Dg(e,t){og(e),sg(`fadeIn`,t);let n=Tg(e,Sg(1.7+t));return wg(e.seconds,xg((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const Og={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function kg(e,t){og(e),sg(`dissolveOut`,t);let n=Sg(9.3+t),r=Tg(e,Sg(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Og;return wg(e.seconds,xg((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=ug((f-a)/(o-a)),m=i*Jh(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Ag=[211,337],jg=(e,t)=>({row:e.row,centre:e.col+t/2});function Mg(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?jg(e,a):p(o)}}function Ng(e,t){og(e),sg(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>Gh(r/Ag[0],n/24+5.9,t+e/24+2.3)+.5*Gh(r/Ag[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new qc;return rg(e=>{let{colors:t,fills:n,depth:r,theme:o}=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=a.get(o,()=>new Kc).get(eg(e),()=>zg(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})),d=Hg(r,o),f=Mg(e);return G.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=Pg(t,i(a,e));return Ug(o.looks,t,r===V.TRUECOLOR?o.either.map(Bg):d,u.get(l(t,n))??Ig)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Pg(e,t){if(t===0)return{looks:e,either:[e]};let n=ju.fromRgba(e),r=bl(e),i=e=>new ju(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]=bl(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Fg=e=>Math.log(xl(e,new B(0,0,0))),Ig={lo:-1/0,hi:1/0},Lg={lo:1/0,hi:-1/0},Rg=Math.log(1.031);function zg(e,t,n){let r=new Map;for(let i of e.filter(e=>Xh(e,t)>1)){let e=(Math.log(xl(i.fg,i.bg))-Math.log(Xh(i,t)))/Zh.filter(e=>n(i,e)!==void 0).length;for(let t of Zh){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Fg(i[t]),Fg(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Ig;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<Rg?Lg:{lo:t,hi:n}]))}const Bg=e=>({color:e,looks:ju.fromRgba(e),stop:Fg(e)}),Vg=new qc;function Hg(e,t){return Vg.get(H.indexed(e,t),e=>e.map(([,e])=>Bg(e)))}function Ug(e,t,n,{lo:r,hi:i}){return Wg(e,[Bg(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function Wg(e,t){let n=ju.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]}function Gg({attribute:e,off:t,on:n}){let r=yf([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>G.map(r,e=>i[e])}const Kg={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},qg={loops:{shimmer:(e,t=cg.shimmer)=>$h(yg(t,24,lg.sun,e.z)),pulse:(e,t=cg.pulse)=>$h(_g(t,lg.sun,e.z)),sparkle:(e,t=cg.sparkle)=>$h(bg(t,lg.firefly,e.z)),wheel:(e,t=cg.wheel)=>Ng(t,e.z)},transitions:{fade:(e,t=cg.fade)=>Dg(t,e.z),dissolve:(e,t=cg.dissolve)=>kg(t,e.z)},attributes:{blink:()=>Gg(Kg.blink),boldPulse:()=>Gg(Kg.boldPulse)}};function Jg(e,t){let n=0,r=Sh(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:yh(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function Yg(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:$g(t,n)));return e_(e.flat(),n.flat()),n}function Xg(e,t,n){let{placed:r,cells:i}=Jg([new W(e.plain)],n.key);return G.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>Zg(e,r[0],Yg(r,t)[0]))}function Zg(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const Qg=Jc(/[\n\t]/);function $g(e,t){let n=e(t);if(n===t.glyph)return n;if(z(n)!==z(t.glyph)||Qg.test(n)||qp(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${z(t.glyph)} cell(s) wide, with no line break or control character`);return n}function e_(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if(cl(o+t+s).length!==cl(o).length+cl(t).length+cl(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function t_(e){return` `.repeat(z(e))}function n_(e){let t=new Map;for(let n of e.filter(e=>Ch(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&z(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function r_(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function i_(e){let t=yf([e]);return(n,r)=>G.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>G.constant(r)})}const a_=e=>e.glyph;function o_(e){let t=bf.once(0,e.seconds),n=Vd(e.ease);return wg(e.seconds,({cells:e})=>{let{length:r,place:i}=n_(e);return G.continuous(e=>{let a=r_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:t_(e.glyph)})})}const s_=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],c_=1/15;function l_(e,t){sg(`scramble`,t);let n=bf.once(0,e.seconds),r=Vd(e.ease),i=i_(c_)(e=>e,0);return wg(e.seconds,({cells:e})=>{let{length:a,place:o}=n_(e);return G.continuous(e=>{let s=r_(a,r(n(e))),c=i.at(e);return e=>!Ch(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:u_(e,t,c)})})}function u_(e,t,n){let r=r=>s_[Math.floor(qh(e.seed*7919+r,t+n*.618)*s_.length)];return Array.from({length:z(e.glyph)},(e,t)=>r(t)).join(``)}function d_(e){let t=bf.once(0,e.seconds),n=Vd(e.ease);return wg(e.seconds,({cells:e})=>{let{length:r,place:i}=n_(e);return G.continuous(e=>{let a=r-r_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:t_(e.glyph)})})}const f_=.3;function p_(e,t){sg(`scrambleOut`,t);let n=bf.once(0,e.seconds),r=Vd(e.ease),i=i_(c_)(e=>e,0);return wg(e.seconds,({cells:e})=>{let{length:a,place:o}=n_(e);return G.continuous(e=>{let s=r(n(e)),c=r_(a,s/(1-f_)),l=r_(a,(s-f_)/(1-f_)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?t_(e.glyph):!Ch(e.glyph)||n>=c?e.glyph:u_(e,t,u)}})})}function m_(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return z(t)===z(e)?t:e}function h_({step:e,width:t},n){if(uf(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);sg(`caseWave`,n);let r=i_(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+z(t.glyph)),0)+t,a=Math.floor(qh(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+z(e.glyph)>n-t?m_(e.glyph):e.glyph},a_)}}function g_(e,t){let n=e=>{let t=cl(e);if(t.length===0||t.some(e=>z(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!Gf(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);uf(`particles step`,e.step),sg(`particles`,t);let a=i_(e.step);return({asciiOnly:n})=>{let o=Kf({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Ch(n.glyph)||z(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return qh(a,s)<e.density?o[Math.floor(qh(a,s+3.1)*o.length)]+t_(n.glyph).slice(1):n.glyph}},a_)}}const __={typewriter:{seconds:2,ease:sf.linear},scramble:{seconds:2.5,ease:sf[`ease-in`]},backspace:{seconds:1.5,ease:sf.linear},scrambleOut:{seconds:2.5,ease:sf[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},v_={loops:{wave:e=>h_(__.wave,e.z),rain:e=>g_(__.rain,e.z),stars:e=>g_(__.stars,e.z)},transitions:{typewriter:(e,t=__.typewriter)=>o_(t),scramble:(e,t=__.scramble)=>l_(t,e.z),backspace:(e,t=__.backspace)=>d_(t),scrambleOut:(e,t=__.scrambleOut)=>p_(t,e.z)}};var y_=class{beat;width;_shown;constructor(e){this.beat=yf(e.map(e=>e.seconds));let t=e.map(e=>hh(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)}reduced(){return G.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return xp(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function b_(e,t,n){let r=mp(e,t,n),i=r.value.copy();return i.style=Mf(i.style,gp(hp(r,t))),i}function x_(e,t){let n=[...ip(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const S_={segments:[],width:0},C_={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function w_(e,t){return C_[e](t)}function T_(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 E_=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`}*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=>x_(cm(t),e)),o=n=>i?x_(sm(i,null,t[n],{index:n}),e):S_,s=n=>i?x_(sm(i,t[n],null,{index:n+1}),e):S_,c=(n,r)=>i?x_(sm(i,t[n],t[r],{index:r}),e):S_,l=[],u=null,d=r>0?{segments:[new W(` `.repeat(r))],width:r}:S_;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=w_(p,i),o=T_(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=x_(t[i],e).width,o=this.joiner?x_(sm(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?x_(sm(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+=x_(sm(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=x_(sm(this.joiner,null,t[0],{index:0}),e).width,r+=x_(sm(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function D_(){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 O_=(e,t)=>e===t;function k_(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const A_=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),j_=[`primary`,`secondary`,`accent`],M_=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],N_={"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`},P_=(e,t)=>`${e}${N_[t]}`,F_=(e,t,n,r)=>kv(e,n,r),I_=(e,t,n,r)=>jv(e,e.get(`text-${t}`),n,r),L_=e=>({tones:[M_[e],M_[e+2],M_[e+1]],text:F_,activated:`muted`}),R_=e=>({tones:[M_[3-e],M_[3+e],M_[3]],text:F_,activated:`muted`}),z_=e=>({tones:[M_[3-e],M_[3+e]],text:F_,activated:`muted`}),B_={wide:R_(2),widest:R_(3),pair:z_(2),"pair-wide":z_(3)},V_=Object.keys(B_),H_={muted:{tones:[`muted`,`base`],text:I_,activated:`lighten-2`},deepest:L_(0),deeper:L_(1),middle:L_(2),brighter:L_(3),brightest:L_(4),...B_},U_=(e,t)=>e[t%e.length],W_=`accent`,G_=1/0,K_={keystones:[],open:[`accent`,`primary`,`secondary`]},q_={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},J_={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function Y_(){let e=Object.entries(q_).flatMap(([e,t])=>Object.entries(J_).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:G_,keystones:t,open:r}]));return Object.fromEntries(e)}const X_=Y_(),Z_={accent:{hues:[`secondary`,`accent`],run:G_,...K_},duo:{hues:[`primary`,`secondary`],run:G_,...K_},mono:{hues:[`primary`],run:G_,...K_},alt:{hues:[`secondary`,`accent`],run:3,...K_},...X_},Q_=Object.keys(X_),$_=(e,t,n)=>Tv(e,t,t.variation.hues.flatMap(r=>{let i=ev(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function ev(e,t,n,r){return rv(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=iv(e,t,r),a=nv(n.tones.length,new Set(M_.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return tv(Array.from({length:a-c.length}).reduce(a=>{let o=av(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const tv=e=>{if(e.length<3)return e;let t=M_,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},nv=(e,t)=>Math.max(2,Math.min(e,t-1)),rv=D_(),iv=(e,t,n)=>r=>Gu(e.get(P_(t,r)),n).hex;function av(e,t,n,r,i){let a=iv(e,t,i);return ov(n,e.dark).find(e=>!r.includes(a(e)))}function ov(e,t){let n=M_,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return M_.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const sv=(e,t)=>Math.floor(e*t),cv=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},lv=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},uv=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],dv=e=>typeof e==`string`&&uv.includes(e),fv={"van-der-corput":{place:lv,quantize:cv},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:sv},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:sv},monotonic:{place:(e,t)=>(e+.5)/t,quantize:sv},uniform:{place:()=>.5,quantize:cv}},pv=e=>fv[e??`van-der-corput`];function mv(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function hv(e,t){let n=e[mv(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function gv(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const _v=(e,t)=>mv(t,e.hues.length);function vv(e,t,n,r){let{row:i,cell:a}=gv(n);return a===void 0?yv(e,t,i,a,r):bv(e,t,i,a,r)[a.index-a.lineStart]}function yv(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(_v(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>Ev[e](n,r))?W_:l;return{hue:u,shade:hv(ev(e,u,t.shade,i),r)}}function bv(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return xv(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:Sv(n),Sv(r,r.lineStart),i].join(`|`),()=>Tv(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>yv(e,t,n,{...r,index:r.lineStart+o},i)),i))}const xv=D_();function Sv({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${Cv(r)},${i},${a}`}function Cv(e){let t=wv.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const wv=new Map(uv.map(e=>[fv[e],e]));function Tv(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&iv(e,n.hue,r)(n.shade)},o=Lv(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=ev(e,s,t.shade,r),u=l.find(t=>!c.includes(iv(e,s,r)(t)))??av(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const Ev={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},Dv=(e,t)=>e.get(P_(t.hue,t.shade)),Ov=4.5;function kv(e,t,n){return Av(e,`${t.hex}|${n}`,()=>{let r=Hu(t);return jv(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>xl(r,t)<xl(r,e)?t:e),t,n)})}const Av=D_();function jv(e,t,n,r){return Mv(e,`${t.hex}|${n.hex}|${r}`,()=>Uu(t,n,Ov,r))}const Mv=D_(),Nv=({decor:e,depth:t})=>U_(e.variation.open,t),Pv=(e,t,n)=>ev(e,Nv(t),t.decor.shade,n).map(e=>({hue:Nv(t),shade:e}));function Fv(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return Iv(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=Nv(t),c=t=>ev(e,t,o,n).map(iv(e,t,n)),l=a.keystones.length>0?[W_]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(Nv(t)),Lv(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(iv(e,s,n)(o.activated))?av(e,s,[o.activated],d,n)??o.activated:o.activated})}const Iv=D_(),Lv=(e,t,n)=>iv(e,Nv(t),n)(Fv(e,t,n)),Rv=e=>({...e,depth:e.depth+1});function zv(e,t,n){return{state:e.get(P_(Nv(t),Fv(e,t,n))),plane:e.get(`surface`),items:Pv(e,t,n).map(t=>Dv(e,t))}}function Bv(e,t,n,r){return hv(zv(e,t,r).items,n)}function Vv(e,t,n,r){let i=Bv(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,Nv(t),i,r)}}function Hv(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&Kv(e,t);case`band`:return t.kind===`band`&&qv(e,t)}}const Uv=A_(k_({index:O_,count:O_,distribution:O_,axis:O_,lineStart:O_,lineEnd:O_})),Wv=k_({variation:O_,shade:O_}),Gv=k_({decor:Wv,depth:O_}),Kv=k_({kind:O_,decor:Wv,address:Uv}),qv=k_({kind:O_,band:Gv,address:Uv}),Jv=e=>({kind:`bar`,decor:e,address:[]}),Yv=(e,t)=>({...e,address:[...e.address,t]}),Xv=e=>({kind:`band`,band:e,address:[]});function Zv(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=vv(e,r,i,n),o=Dv(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...Vv(e,r,gv(i).cell,n),disclosure:Rv(r)}}}}const Qv=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function $v(e){let t=typeof e==`string`?Qv.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const ey=`textual-dark`;function ty(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function ny(){return Td()}function ry(){return[`bar`,...ny()]}let iy;function ay(e){return iy??=new Set(ry()),iy.has(e)}function oy(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return ty(e===void 0?null:a(e),t,a(n??r),r,a)}const sy=[`style`,`palette`,`effect`];function cy(e){return e!==void 0&&e.includes(`{{`)}function ly(e,t,n,r,i){let a=cy(n)?{kind:`expression`,source:n}:i(n??r.name);return ty(e===void 0?null:i(e),t,a,r,i)}const uy=`none`;function dy(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function fy(e,t){return dy(e,t)??dy(`none`,t)??{kind:`decided`,name:`none`,value:yu}}function py(e,t,n,r){return ly(e,t,n,fy(uy,r),e=>dy(e,r))}const my=`none`,hy={style:uy,palette:ey,effect:my};function gy(e,t,n){return`${e} rendered "${hy[t]}": ${n}`}const _y=Object.freeze([my,...Object.keys(qg.loops)]),vy=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),yy=Object.keys(vy),by=Object.freeze([`bar`,..._y]);function xy(e){let t=_y.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Sy(e){return xy(e)??{kind:`decided`,name:`none`,value:`none`}}function Cy(e,t,n){return ly(e,t,n,Sy(my),xy)}const wy=Object.freeze(Object.keys(dh)),Ty=[`powerline`,`capsule`,`plain`];function Ey(e){return Ty.includes(e)}const Dy=[`truecolor`,`256`,`ansi`,`none`];function Oy(e){return Dy.includes(e)}function ky(e){return Pl(e)??V.DEFAULT}const Ay=Object.keys(Z_),jy=Object.keys(H_),My=`true`,Ny=`false`,Py=[My,Ny],Fy={min:0,max:16};function Iy(e){return e===`true`?!0:e===`false`?!1:null}function Ly(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const Ry=[`vertical`,`horizontal`],zy={vertical:`row`,horizontal:`cell`};function By(e){return e.id??e.name}function Vy(e){return[...Wy(e)].flatMap(e=>e.kind===`segment`?[By(e)]:[])}function Hy(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Uy(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*Wy(e){yield e;for(let t of Jy(e))yield*Wy(t)}const Gy=(e,t)=>`${e}.children[${t}]`,Ky=e=>`${e}.opens.body`;function*qy(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*qy(r,Gy(t,n));else e.opens!==void 0&&(yield*qy(e.opens.body,Ky(t)))}function Jy(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function Yy(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const Xy=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Zy(e){return e.kind===`file`||e.kind===`shell`}function Qy(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return Zy(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function $y(e){let t=[];return Qy(e,(e,n)=>(t.push([n,e]),e)),t}const eb=[`fail`,`ignore`];function tb(e){return e.missingData??`fail`}function*nb(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 rb=`theme`,ib=`effect`,ab=[rb,ib];function ob(e){return{...e.settings,[rb]:{label:rb,domain:`theme`,default:e.palette??`bar`},[ib]:{label:ib,domain:by,default:`bar`}}}function sb(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function cb(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=sb(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 lb(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&ay(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function ub(e){return String(e)}function db(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Ly(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return lb(e,r)?r:void 0}function Eee(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:db(n,o))??i}function fb(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 Dee=[`left`,`center`,`right`],Oee=[`right`,`left`,`middle`];var pb=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Iee(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},kee=class extends pb{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
|
|
54
|
+
`?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Ch(e){return e.trim()!==``}function wh(e){let t=Sh(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Th(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&Sf(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&Sf(t.anchor,i))return t}}}function Eh(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Dh(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||Eh(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Ch(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Ch(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Oh(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>G.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function kh(e,t){return t?{fg:e.bg,bg:e.fg}:e}function Ah(e,t,n,r){let i=t.bg.compositeOver(yl),a=t.fg.compositeOver(i);return{fg:H.matchMove(e.fg,a,n,r,!0),bg:H.matchMove(e.bg,i,n,r,!1)}}function jh(e,t){return Mh(e.color,t.color,!0)&&Mh(e.bgcolor,t.bgcolor,!1)}function Mh(e,t,n){return e===t||Nh(e,n)===Nh(t,n)}function Nh(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function Ph(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const Fh=wf.filter(e=>e!==`reverse`);function Ih(e){return Object.fromEntries(Fh.map(t=>[t,e[t]]))}function Lh(e,t){return e===t||Fh.every(n=>e[n]===t[n])}function Rh(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function zh(e,t){return Bh(e.fg,t.fg)&&Bh(e.bg,t.bg)}function Bh(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const Vh=(()=>{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]})(),Hh=e=>e*e*e*(e*(e*6-15)+10),Uh=(e,t,n)=>e+n*(t-e);function Wh(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 Gh(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=Hh(e),u=Hh(t),d=Hh(n),f=Vh[o]+s,p=Vh[f]+c,m=Vh[f+1]+c,h=Vh[o+1]+s,g=Vh[h]+c,_=Vh[h+1]+c;return Uh(Uh(Uh(Wh(Vh[p],e,t,n),Wh(Vh[g],e-1,t,n),l),Uh(Wh(Vh[m],e,t-1,n),Wh(Vh[_],e-1,t-1,n),l),u),Uh(Uh(Wh(Vh[p+1],e,t,n-1),Wh(Vh[g+1],e-1,t,n-1),l),Uh(Wh(Vh[m+1],e,t-1,n-1),Wh(Vh[_+1],e-1,t-1,n-1),l),u),d)}function Kh(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*Gh(e*r,t*r,n*r),o+=a,a/=2}return i/o}function qh(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function Jh(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const Yh=Array.from({length:48},(e,t)=>(t+1)/48);function Xh(e,t){return Math.min(xl(e.fg,e.bg),4.5)-(t===V.TRUECOLOR?.01:0)}const Zh=[`fg`,`bg`];function Qh({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=>Zh.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=>ju.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=Zh.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=Xh(r,t),c=(t,n)=>ag(i,r[t],(t===a?e:o)*n);return Yh.every(e=>{let i=vh.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return xl(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 $h(e,t){let n=new qc;return rg(ng(e,r=>{let i=t??r.colors,a=[eg(r),`|`,...i].join(` `);return n.get(r.theme,()=>new Kc).get(a,()=>Qh(r,i,e.touch))}))}function eg({depth:e,pairs:t}){return[e,...t.map(tg)].join(` `)}function tg({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function ng(e,t){return n=>{let r=t(n);return G.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(ug(i(n))*48)/48,o=(t,n)=>ag(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function rg(e){return t=>ig(t.depth)?G.constant(e=>e):e(t)}function ig(e){switch(e){case V.DEFAULT:case V.STANDARD:case V.WINDOWS:return!0;case V.EIGHT_BIT:case V.TRUECOLOR:return!1}}function ag(e,t,n){return n===0?t:e(t,n)}function og(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}`)}function sg(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const cg={shimmer:{seconds:109,ease:sf.linear,swing:.9},pulse:{seconds:43,ease:sf.linear,swing:.85},sparkle:{seconds:139,ease:sf.linear,swing:.95},wheel:{seconds:907,ease:sf.linear,swing:1},fade:{seconds:20,ease:sf[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:sf[`ease-in-out`],swing:1}},lg={sun:new B(255,228,176),firefly:new B(222,245,140)},ug=e=>Math.min(1,Math.max(0,e));function dg(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 ju((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function fg(e){let t=ju.fromRgba(e);return(e,n)=>{let r=ju.fromRgba(e);return dg(r,new ju(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const pg=(e,t)=>t*e[e.length-1][0];function mg(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 hg(e,t,n){let r=pg(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=mg(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const gg=[[.24,1],[.6,0]];function _g(e,t,n){og(e),sg(`pulse`,n);let r=.9+.2*qh(n,3.1),i=t=>.1*Gh(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:fg(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*Jh(-.5,.5,Gh(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 vg=e=>Math.abs(e)>=1?0:(1-e*e)**3;function yg(e,t,n,r){og(e),sg(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>Jh(-.4,.4,Gh(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(qh(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*qh(e,8.5+r))),p=i*u/80*(c+l*qh(e,5.5+r)),m=ug((n-(e+s*qh(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*Gh(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(-((Gh(e,t,n)/.8)**2));return{touch:fg(n),field:(n,i)=>{let[a,o]=Eg(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*vg((i.col-a-n)/t));let c=i.row+r,l=.8*Gh(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 bg(e,t,n){og(e),sg(`sparkle`,n);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*Gh(e*1.7+.2,.3+t*2.9,.5+n),l=i+qh(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=qh(u,s+1)<.15?0:1,f=.5+.5*qh(u,s+2),p=qh(u,s+3)*(1-pg(gg,f)),m=l/r-u-p;return{x:a+c*8+5*(2*qh(u,s+4)-1)+5*f*(2*qh(u,s+5)-1)*hg(gg,m,f)+1.5*Gh(s,.1,i*.035),y:o+t*3+.6*Gh(s,2.2,i*.035),glow:d*mg(gg,m,f)}};return{touch:fg(t),field:(t,n)=>{let r=n.cells(),[s,c]=Eg(r.map(e=>e.col)),[l,u]=Eg(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*vg(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function xg(e,t){return n=>{let r=ju.fromRgba(n.theme.backgroundColor);return G.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-ug(a(n)));if(i===0)return e;let o=dg(ju.fromRgba(e.bg),r,i);return{...e,fg:dg(ju.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Sg(e){return t=>ug(.5+1.1*Kh(t.col*.09+1.4*Gh(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var Cg=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return G.done(this.schedule,e)}};function wg(e,t){let n=G.of({...G.sequence(G.continuous(()=>void 0),e,G.constant(void 0)),reduced:()=>G.cut(void 0,void 0)}),r=new Cg(i=>{let a=t(i);return G.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>G.cut(a.at(0),a.at(e))})},n);return r}function Tg(e,t){return(n,r)=>{let[i,a]=Eg(r.map(t)),o=(a>i?.55:0)*e.seconds,s=bf.once(0,e.seconds-o);return e=>{let r=a>i?ug((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function Eg(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 Dg(e,t){og(e),sg(`fadeIn`,t);let n=Tg(e,Sg(1.7+t));return wg(e.seconds,xg((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const Og={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function kg(e,t){og(e),sg(`dissolveOut`,t);let n=Sg(9.3+t),r=Tg(e,Sg(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Og;return wg(e.seconds,xg((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=ug((f-a)/(o-a)),m=i*Jh(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Ag=[211,337],jg=(e,t)=>({row:e.row,centre:e.col+t/2});function Mg(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?jg(e,a):p(o)}}function Ng(e,t){og(e),sg(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>Gh(r/Ag[0],n/24+5.9,t+e/24+2.3)+.5*Gh(r/Ag[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new qc;return rg(e=>{let{colors:t,fills:n,depth:r,theme:o}=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=a.get(o,()=>new Kc).get(eg(e),()=>zg(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})),d=Hg(r,o),f=Mg(e);return G.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=Pg(t,i(a,e));return Ug(o.looks,t,r===V.TRUECOLOR?o.either.map(Bg):d,u.get(l(t,n))??Ig)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Pg(e,t){if(t===0)return{looks:e,either:[e]};let n=ju.fromRgba(e),r=bl(e),i=e=>new ju(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]=bl(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Fg=e=>Math.log(xl(e,new B(0,0,0))),Ig={lo:-1/0,hi:1/0},Lg={lo:1/0,hi:-1/0},Rg=Math.log(1.031);function zg(e,t,n){let r=new Map;for(let i of e.filter(e=>Xh(e,t)>1)){let e=(Math.log(xl(i.fg,i.bg))-Math.log(Xh(i,t)))/Zh.filter(e=>n(i,e)!==void 0).length;for(let t of Zh){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Fg(i[t]),Fg(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Ig;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<Rg?Lg:{lo:t,hi:n}]))}const Bg=e=>({color:e,looks:ju.fromRgba(e),stop:Fg(e)}),Vg=new qc;function Hg(e,t){return Vg.get(H.indexed(e,t),e=>e.map(([,e])=>Bg(e)))}function Ug(e,t,n,{lo:r,hi:i}){return Wg(e,[Bg(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function Wg(e,t){let n=ju.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]}function Gg({attribute:e,off:t,on:n}){let r=yf([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>G.map(r,e=>i[e])}const Kg={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},qg={loops:{shimmer:(e,t=cg.shimmer)=>$h(yg(t,24,lg.sun,e.z)),pulse:(e,t=cg.pulse)=>$h(_g(t,lg.sun,e.z)),sparkle:(e,t=cg.sparkle)=>$h(bg(t,lg.firefly,e.z)),wheel:(e,t=cg.wheel)=>Ng(t,e.z)},transitions:{fade:(e,t=cg.fade)=>Dg(t,e.z),dissolve:(e,t=cg.dissolve)=>kg(t,e.z)},attributes:{blink:()=>Gg(Kg.blink),boldPulse:()=>Gg(Kg.boldPulse)}};function Jg(e,t){let n=0,r=Sh(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:yh(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function Yg(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:$g(t,n)));return e_(e.flat(),n.flat()),n}function Xg(e,t,n){let{placed:r,cells:i}=Jg([new W(e.plain)],n.key);return G.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>Zg(e,r[0],Yg(r,t)[0]))}function Zg(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const Qg=Jc(/[\n\t]/);function $g(e,t){let n=e(t);if(n===t.glyph)return n;if(z(n)!==z(t.glyph)||Qg.test(n)||qp(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${z(t.glyph)} cell(s) wide, with no line break or control character`);return n}function e_(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if(cl(o+t+s).length!==cl(o).length+cl(t).length+cl(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function t_(e){return` `.repeat(z(e))}function n_(e){let t=new Map;for(let n of e.filter(e=>Ch(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&z(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function r_(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function i_(e){let t=yf([e]);return(n,r)=>G.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>G.constant(r)})}const a_=e=>e.glyph;function o_(e){let t=bf.once(0,e.seconds),n=Vd(e.ease);return wg(e.seconds,({cells:e})=>{let{length:r,place:i}=n_(e);return G.continuous(e=>{let a=r_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:t_(e.glyph)})})}const s_=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],c_=1/15;function l_(e,t){sg(`scramble`,t);let n=bf.once(0,e.seconds),r=Vd(e.ease),i=i_(c_)(e=>e,0);return wg(e.seconds,({cells:e})=>{let{length:a,place:o}=n_(e);return G.continuous(e=>{let s=r_(a,r(n(e))),c=i.at(e);return e=>!Ch(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:u_(e,t,c)})})}function u_(e,t,n){let r=r=>s_[Math.floor(qh(e.seed*7919+r,t+n*.618)*s_.length)];return Array.from({length:z(e.glyph)},(e,t)=>r(t)).join(``)}function d_(e){let t=bf.once(0,e.seconds),n=Vd(e.ease);return wg(e.seconds,({cells:e})=>{let{length:r,place:i}=n_(e);return G.continuous(e=>{let a=r-r_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:t_(e.glyph)})})}const f_=.3;function p_(e,t){sg(`scrambleOut`,t);let n=bf.once(0,e.seconds),r=Vd(e.ease),i=i_(c_)(e=>e,0);return wg(e.seconds,({cells:e})=>{let{length:a,place:o}=n_(e);return G.continuous(e=>{let s=r(n(e)),c=r_(a,s/(1-f_)),l=r_(a,(s-f_)/(1-f_)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?t_(e.glyph):!Ch(e.glyph)||n>=c?e.glyph:u_(e,t,u)}})})}function m_(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return z(t)===z(e)?t:e}function h_({step:e,width:t},n){if(uf(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);sg(`caseWave`,n);let r=i_(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+z(t.glyph)),0)+t,a=Math.floor(qh(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+z(e.glyph)>n-t?m_(e.glyph):e.glyph},a_)}}function g_(e,t){let n=e=>{let t=cl(e);if(t.length===0||t.some(e=>z(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!Gf(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);uf(`particles step`,e.step),sg(`particles`,t);let a=i_(e.step);return({asciiOnly:n})=>{let o=Kf({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Ch(n.glyph)||z(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return qh(a,s)<e.density?o[Math.floor(qh(a,s+3.1)*o.length)]+t_(n.glyph).slice(1):n.glyph}},a_)}}const __={typewriter:{seconds:2,ease:sf.linear},scramble:{seconds:2.5,ease:sf[`ease-in`]},backspace:{seconds:1.5,ease:sf.linear},scrambleOut:{seconds:2.5,ease:sf[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},v_={loops:{wave:e=>h_(__.wave,e.z),rain:e=>g_(__.rain,e.z),stars:e=>g_(__.stars,e.z)},transitions:{typewriter:(e,t=__.typewriter)=>o_(t),scramble:(e,t=__.scramble)=>l_(t,e.z),backspace:(e,t=__.backspace)=>d_(t),scrambleOut:(e,t=__.scrambleOut)=>p_(t,e.z)}};var y_=class{beat;width;_shown;constructor(e){this.beat=yf(e.map(e=>e.seconds));let t=e.map(e=>hh(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)}reduced(){return G.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return xp(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function b_(e,t,n){let r=mp(e,t,n),i=r.value.copy();return i.style=Mf(i.style,gp(hp(r,t))),i}function x_(e,t){let n=[...ip(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const S_={segments:[],width:0},C_={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function w_(e,t){return C_[e](t)}function T_(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 E_=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`}*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=>x_(cm(t),e)),o=n=>i?x_(sm(i,null,t[n],{index:n}),e):S_,s=n=>i?x_(sm(i,t[n],null,{index:n+1}),e):S_,c=(n,r)=>i?x_(sm(i,t[n],t[r],{index:r}),e):S_,l=[],u=null,d=r>0?{segments:[new W(` `.repeat(r))],width:r}:S_;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=w_(p,i),o=T_(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=x_(t[i],e).width,o=this.joiner?x_(sm(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?x_(sm(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+=x_(sm(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=x_(sm(this.joiner,null,t[0],{index:0}),e).width,r+=x_(sm(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function D_(){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 O_=(e,t)=>e===t;function k_(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const A_=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),j_=[`primary`,`secondary`,`accent`],M_=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],N_={"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`},P_=(e,t)=>`${e}${N_[t]}`,F_=(e,t,n,r)=>kv(e,n,r),I_=(e,t,n,r)=>jv(e,e.get(`text-${t}`),n,r),L_=e=>({tones:[M_[e],M_[e+2],M_[e+1]],text:F_,activated:`muted`}),R_=e=>({tones:[M_[3-e],M_[3+e],M_[3]],text:F_,activated:`muted`}),z_=e=>({tones:[M_[3-e],M_[3+e]],text:F_,activated:`muted`}),B_={wide:R_(2),widest:R_(3),pair:z_(2),"pair-wide":z_(3)},V_=Object.keys(B_),H_={muted:{tones:[`muted`,`base`],text:I_,activated:`lighten-2`},deepest:L_(0),deeper:L_(1),middle:L_(2),brighter:L_(3),brightest:L_(4),...B_},U_=(e,t)=>e[t%e.length],W_=`accent`,G_=1/0,K_={keystones:[],open:[`accent`,`primary`,`secondary`]},q_={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},J_={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function Y_(){let e=Object.entries(q_).flatMap(([e,t])=>Object.entries(J_).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:G_,keystones:t,open:r}]));return Object.fromEntries(e)}const X_=Y_(),Z_={accent:{hues:[`secondary`,`accent`],run:G_,...K_},duo:{hues:[`primary`,`secondary`],run:G_,...K_},mono:{hues:[`primary`],run:G_,...K_},alt:{hues:[`secondary`,`accent`],run:3,...K_},...X_},Q_=Object.keys(X_),$_=(e,t,n)=>Tv(e,t,t.variation.hues.flatMap(r=>{let i=ev(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function ev(e,t,n,r){return rv(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=iv(e,t,r),a=nv(n.tones.length,new Set(M_.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return tv(Array.from({length:a-c.length}).reduce(a=>{let o=av(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const tv=e=>{if(e.length<3)return e;let t=M_,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},nv=(e,t)=>Math.max(2,Math.min(e,t-1)),rv=D_(),iv=(e,t,n)=>r=>Gu(e.get(P_(t,r)),n).hex;function av(e,t,n,r,i){let a=iv(e,t,i);return ov(n,e.dark).find(e=>!r.includes(a(e)))}function ov(e,t){let n=M_,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return M_.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const sv=(e,t)=>Math.floor(e*t),cv=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},lv=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},uv=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],dv=e=>typeof e==`string`&&uv.includes(e),fv={"van-der-corput":{place:lv,quantize:cv},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:sv},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:sv},monotonic:{place:(e,t)=>(e+.5)/t,quantize:sv},uniform:{place:()=>.5,quantize:cv}},pv=e=>fv[e??`van-der-corput`];function mv(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function hv(e,t){let n=e[mv(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function gv(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const _v=(e,t)=>mv(t,e.hues.length);function vv(e,t,n,r){let{row:i,cell:a}=gv(n);return a===void 0?yv(e,t,i,a,r):bv(e,t,i,a,r)[a.index-a.lineStart]}function yv(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(_v(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>Ev[e](n,r))?W_:l;return{hue:u,shade:hv(ev(e,u,t.shade,i),r)}}function bv(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return xv(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:Sv(n),Sv(r,r.lineStart),i].join(`|`),()=>Tv(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>yv(e,t,n,{...r,index:r.lineStart+o},i)),i))}const xv=D_();function Sv({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${Cv(r)},${i},${a}`}function Cv(e){let t=wv.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const wv=new Map(uv.map(e=>[fv[e],e]));function Tv(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&iv(e,n.hue,r)(n.shade)},o=Iv(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=ev(e,s,t.shade,r),u=l.find(t=>!c.includes(iv(e,s,r)(t)))??av(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const Ev={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},Dv=(e,t)=>e.get(P_(t.hue,t.shade)),Ov=4.5;function kv(e,t,n){return Av(e,`${t.hex}|${n}`,()=>{let r=Hu(t);return jv(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>xl(r,t)<xl(r,e)?t:e),t,n)})}const Av=D_();function jv(e,t,n,r){return Eee(e,`${t.hex}|${n.hex}|${r}`,()=>Uu(t,n,Ov,r))}const Eee=D_(),Mv=({decor:e,depth:t})=>U_(e.variation.open,t),Nv=(e,t,n)=>ev(e,Mv(t),t.decor.shade,n).map(e=>({hue:Mv(t),shade:e}));function Pv(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return Fv(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=Mv(t),c=t=>ev(e,t,o,n).map(iv(e,t,n)),l=a.keystones.length>0?[W_]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(Mv(t)),Iv(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(iv(e,s,n)(o.activated))?av(e,s,[o.activated],d,n)??o.activated:o.activated})}const Fv=D_(),Iv=(e,t,n)=>iv(e,Mv(t),n)(Pv(e,t,n)),Lv=e=>({...e,depth:e.depth+1});function Rv(e,t,n){return{state:e.get(P_(Mv(t),Pv(e,t,n))),plane:e.get(`surface`),items:Nv(e,t,n).map(t=>Dv(e,t))}}function zv(e,t,n,r){return hv(Rv(e,t,r).items,n)}function Bv(e,t,n,r){let i=zv(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,Mv(t),i,r)}}function Vv(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&Gv(e,t);case`band`:return t.kind===`band`&&Kv(e,t)}}const Hv=A_(k_({index:O_,count:O_,distribution:O_,axis:O_,lineStart:O_,lineEnd:O_})),Uv=k_({variation:O_,shade:O_}),Wv=k_({decor:Uv,depth:O_}),Gv=k_({kind:O_,decor:Uv,address:Hv}),Kv=k_({kind:O_,band:Wv,address:Hv}),qv=e=>({kind:`bar`,decor:e,address:[]}),Jv=(e,t)=>({...e,address:[...e.address,t]}),Yv=e=>({kind:`band`,band:e,address:[]});function Xv(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=vv(e,r,i,n),o=Dv(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...Bv(e,r,gv(i).cell,n),disclosure:Lv(r)}}}}const Zv=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function Qv(e){let t=typeof e==`string`?Zv.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const $v=`textual-dark`;function ey(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function ty(){return Td()}function ny(){return[`bar`,...ty()]}let ry;function iy(e){return ry??=new Set(ny()),ry.has(e)}function ay(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return ey(e===void 0?null:a(e),t,a(n??r),r,a)}const oy=[`style`,`palette`,`effect`];function sy(e){return e!==void 0&&e.includes(`{{`)}function cy(e,t,n,r,i){let a=sy(n)?{kind:`expression`,source:n}:i(n??r.name);return ey(e===void 0?null:i(e),t,a,r,i)}const ly=`none`;function uy(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function dy(e,t){return uy(e,t)??uy(`none`,t)??{kind:`decided`,name:`none`,value:yu}}function fy(e,t,n,r){return cy(e,t,n,dy(ly,r),e=>uy(e,r))}const py=`none`,my={style:ly,palette:$v,effect:py};function hy(e,t,n){return`${e} rendered "${my[t]}": ${n}`}const gy=Object.freeze([py,...Object.keys(qg.loops)]),_y=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),vy=Object.keys(_y),yy=Object.freeze([`bar`,...gy]);function by(e){let t=gy.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function xy(e){return by(e)??{kind:`decided`,name:`none`,value:`none`}}function Sy(e,t,n){return cy(e,t,n,xy(py),by)}const Cy=Object.freeze(Object.keys(dh)),wy=[`powerline`,`capsule`,`plain`];function Ty(e){return wy.includes(e)}const Ey=[`truecolor`,`256`,`ansi`,`none`];function Dy(e){return Ey.includes(e)}function Oy(e){return Pl(e)??V.DEFAULT}const ky=Object.keys(Z_),Ay=Object.keys(H_),jy=`true`,My=`false`,Ny=[jy,My],Py={min:0,max:16};function Fy(e){return e===`true`?!0:e===`false`?!1:null}function Iy(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const Ly=[`vertical`,`horizontal`],Ry={vertical:`row`,horizontal:`cell`};function zy(e){return e.id??e.name}function By(e){return[...Uy(e)].flatMap(e=>e.kind===`segment`?[zy(e)]:[])}function Vy(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Hy(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*Uy(e){yield e;for(let t of qy(e))yield*Uy(t)}const Wy=(e,t)=>`${e}.children[${t}]`,Gy=e=>`${e}.opens.body`;function*Ky(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*Ky(r,Wy(t,n));else e.opens!==void 0&&(yield*Ky(e.opens.body,Gy(t)))}function qy(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function Jy(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const Yy=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Xy(e){return e.kind===`file`||e.kind===`shell`}function Zy(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return Xy(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function Qy(e){let t=[];return Zy(e,(e,n)=>(t.push([n,e]),e)),t}const $y=[`fail`,`ignore`];function eb(e){return e.missingData??`fail`}function*tb(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 nb=`theme`,rb=`effect`,ib=[nb,rb];function ab(e){return{...e.settings,[nb]:{label:nb,domain:`theme`,default:e.palette??`bar`},[rb]:{label:rb,domain:yy,default:`bar`}}}function ob(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function sb(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=ob(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 cb(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&iy(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function lb(e){return String(e)}function ub(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Iy(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return cb(e,r)?r:void 0}function Dee(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:ub(n,o))??i}function db(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 Oee=[`left`,`center`,`right`],kee=[`right`,`left`,`middle`];var fb=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Lee(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},Aee=class extends fb{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
|
|
55
55
|
|
|
56
|
-
`)}},
|
|
57
|
-
`)),this.errors=e,this.name=`DroppedPlacements`}};function q(e,t){return
|
|
58
|
-
`)}function gb(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 ${xb(i)}`,line:q(e.source,[...t.split(`.`),r])}),null)}function Lee(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 ${xb(i)}`,line:q(e.source,[...t.split(`.`),`default`])});return}return i}}function _b(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 ${xb(i)}`,line:q(e.source,[...t.split(`.`),r])});return}return i}}function vb(e,t,n){let r=_b(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${$v(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[...t.split(`.`),`palette`])});return}return r}}function yb(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 ${J(a)}`,line:q(e.source,[...t.split(`.`),r])});return}return a}}function bb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xb(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function J(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Sb(e,t,n,r){return bb(r)?(Tb(e,n,r,t.noun,new Set(Object.keys(t.fields)),Cb(e,t.removed??{},n,r)),wb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${xb(r)}`,line:q(e.source,n.split(`.`))}),null)}function Cb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Eb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function wb(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 Ree=new Set;function Tb(e,t,n,r,i,a=Ree){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:q(e.source,[...t.split(`.`),o])})}function Eb(e,t,n){return e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))}),null}function Db(e,t,n,r){if(!bb(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${xb(r)}`,line:q(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:q(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:q(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:q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function zee(e,t,n,r){if(!bb(r))return e.issues.push({path:n,message:`${n} must be an object, got ${xb(r)}`,line:q(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 ${xb(i)}`,line:q(e.source,n.split(`.`))}),null;let a=t.arms;if(!Object.hasOwn(a,i)){let o=Object.hasOwn(t.retired,i)?t.retired[i](r):`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`;return e.issues.push({path:`${n}.${t.tag}`,message:o,line:q(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 Tb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Bee(e,t,n){return{json:Rb(Ib(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Ob(e){return(...t)=>e()(...t)}function Vee(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:q(n.source,o.split(`.`))}),null}return a}}function kb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>_b(e,t,r,n)}}function Ab(){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 ${xb(i)}`,line:q(e.source,[n])});return}return i}}}}function Hee(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 ${J(o)}`,line:q(e.source,[i])});return}return o}}}}function jb(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 ${J(a)}`,line:q(e.source,[r])});return}return a}}}}function Uee(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>vb(e,t,r)}}function Mb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>gb(e,t,r,n)??void 0}}function Nb(e,t){return re(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Pb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=gb(e,t,r,n);if(i===null)return;let a=Nb(`${t}.${n}`,i);return a===null?i:Eb(e,`${t}.${n}`,a)??void 0}}}function Fb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>yb(t,n,i,r,e)}}function Ib(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 Lb(e){return Ib(e.fields)}function Rb(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function zb(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Bb(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const Vb=[`claude`,`tmux`],Hb=`ne .tmux.pane ""`,Ub={band:{switch:{setting:`experimentalBand`,on:!0,inTmux:!1},label:`🧪 band (A)`,handsOff:!0,rows:null},statusline:{switch:{setting:`experimentalStatusline`,on:!0,inTmux:!1},label:`🧪 statusline (B)`,handsOff:!1,rows:null},pane:{switch:{setting:`experimentalPane`,on:!0,inTmux:!1},label:`🧪 tmux pane (C)`,handsOff:!0,rows:null},tmuxStatus:{switch:{setting:`renderer`,on:`tmux`,inTmux:!0},label:`tmux status line`,handsOff:!0,rows:5}},Wb=Object.keys(Ub),Gb=Wb.filter(e=>Ub[e].switch.on===!0),Kb={by:`request`},qb=e=>`drawing.${e}`,Jb={subscribers:0,fps:0,shown:!0},Yb=(e,t)=>`feeds.${e}.${t}`;function Xb(e){return Object.fromEntries(Wb.map(t=>[t,e(t)]))}const Wee=Xb(()=>Jb);function Zb(e){return typeof e==`string`&&Object.hasOwn(Ub,e)?e:null}const Qb=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),$b=[...Qb(3,1),...Qb(3,.25)],ex=$b.reduce((e,{seconds:t})=>e+t,0),tx={min:15,max:600,step:15},nx=(e,t)=>e+t,rx=e=>e-ex,ix=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),ax=(e,t,n={})=>({spec:Fb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),ox=e=>t=>e.includes(t)?`🧪 ${t}`:t,sx={spec:Ab(),domain:`bool`,parse:Iy},cx=e=>({spec:Hee(e),domain:e,parse:t=>Ly(t,e)});function lx(e,t,n,r={}){return{kind:`session`,...ax(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function ux(e,t){return{kind:`session`,...sx,floor:e,control:t,themeDefault:!1}}function dx(e,t,n){return{kind:`session`,...cx(e),floor:t,control:n,themeDefault:!1}}function fx(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const px=e=>({kind:`text`,spec:e}),mx={required:!1,json:{enum:[...Dy]},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: ${Dy.join(`, `)}`,line:q(e.source,[...t.split(`.`),n])});return}return yb(e,t,r,n,Dy)}},hx={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=_b(e,t,r,n);return cy(i)?i:vb(e,t,r)}},gx={required:!1,json:{anyOf:[{enum:[..._y]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&cy(i)?i:yb(e,t,r,n,_y)}},_x=/^[^\r\n]*\S[^\r\n]*$/u,vx=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),yx={required:!1,json:{type:`string`,pattern:_x.source,not:{pattern:vx.source}},parse:(e,t,n,r)=>{let i=_b(e,t,r,n);if(i===void 0||_x.test(i)&&!vx.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:q(e.source,[...t.split(`.`),n])})}},bx=Object.fromEntries(Gb.map(e=>[Ub[e].switch.setting,ux(!1,ix(Ub[e].label,`toggles`))])),xx={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Sx={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:xx[e]})},Cx={palette:fx(`theme`,hx,{themes:`themes`},ix(`🎨 theme`,`door`)),preset:fx(`preset`,kb(),{from:`presets`},ix(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:fx(`style`,kb(),{from:`styles`},ix(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:fx(`effect`,gx,{from:_y},ix(`✨ effect`,`look`)),endcaps:lx(wy,`powerline`,ix(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:lx(Ay,`accent`,ix(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:ox(Q_),themeDefault:!0}),shade:lx(jy,`middle`,ix(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:ox(V_),themeDefault:!0}),transitions:ux(!1,ix(`fade in/out`,`look`)),animationSpeed:lx(yy,`1x`,ix(`speed`,`look`)),autoWrap:ux(!0,ix(`wrap`,`config`)),padding:dx({...Fy,step:1},1,ix(`padding`,`config`)),updateNotice:ux(!0,ix(`update notice`,`config`)),menuTimeout:dx(tx,120,ix(`menu timeout`,`config`)),renderer:lx(Vb,`claude`,ix(`renderer`,`config`,{shown:Hb}),{optionDomain:`renderers`,library:Sx}),...bx,colorCompatibility:{kind:`config`,...ax(Dy,`colorCompatibilities`),spec:mx,floor:`truecolor`},default_empty_value:px(kb()),default_separator:px(kb()),menuGlyph:px(yx)},wx=Object.entries(Cx),Tx=wx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Gee=wx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Ex=wx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),Kee=wx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Dx(e){return Cx[e]}const Ox=e=>Dx(e).floor;function kx(e){let t=Cx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const Ax=e=>`${e}.effective`,jx=e=>{let t=Cx[e];return t.kind===`selection`?t.sessionKey:e},Mx=Object.fromEntries(Gee.map(e=>{let t=jx(e);return[t,{configKey:e,sessionKey:t,effectiveVar:Ax(t),...Cx[e].control}]})),Nx=Object.keys(Mx),Px=Object.values(Mx),Fx=Tx.filter(e=>Cx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:Ax(e)})),Ix=new Set(Fx.map(e=>e.configKey)),Lx=new Map([...Px,...Fx].map(e=>[e.configKey,e.effectiveVar])),Rx=new Map(Px.map(e=>[e.sessionKey,e.effectiveVar]));function zx(e){return Object.fromEntries(Nx.map(t=>[t,e(t)]))}const Bx=new Map(Nx.map(e=>[Mx[e].sessionKey,e])),Vx=new Map;function Hx(e){let t=Wx(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 Ux(e,t){return e===`bar`?t:Hx(e)}function Wx(e){let t=Vx.get(e);if(t!==void 0)return t;let n=Ed(e);return n===null?null:(Vx.set(e,n),n)}function Gx(e,t){return Kx(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Rd(e,t))}const Kx=D_();function qx(e){let t=Wx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Jx(e,t,n){let r=qx(e);return r===null?(n(gy(t,`palette`,`"${e}" names no installed theme${$v(e)}`)),Xx()):r}function Yx(e,t,n){return ly(e,t,n,Xx(),qx)}function Xx(){return{kind:`decided`,name:ey,value:Hx(ey)}}const Zx=/^[A-Za-z_][A-Za-z0-9_]*$/;function Qx(e){return`#${e+1}`}const $x={rows:{}};function eS(e){return`rows`in e}function tS(e){return Object.fromEntries(e.map((e,t)=>[Qx(t),e]))}function nS(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:tS(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:tS([n])}}function rS(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function iS(e){return eS(e)?rS(e):e}function*aS(e,t){if(!eS(e)){yield*qy(e,t);return}yield[rS(e),t];for(let[n,r]of Object.entries(e.rows))yield*qy(r,`${t}.rows.${n}`)}function oS(e,t){return eS(e)?{...t,...e,rows:{...t.rows,...e.rows}}:nS(e)}function sS(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...Wy(rS(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||By(e)===t.id)))return e;let i=r.find(e=>By(e)===n);if(i!==void 0)return cS(e,t,`as "${n}", but placement "${n}" is already segment "${i.name}" — give the cell its own id`);let a={kind:`segment`,name:t.seg,...t.id!==void 0&&{id:t.id},insertedBy:t.by},o=Object.entries(e.root.rows).map(([e,n])=>[e,n,lS(n,t.anchor,a,t.relation)]);return o.some(([,,e])=>e!==null)?{...e,root:{...e.root,rows:Object.fromEntries(o.map(([e,t,n])=>[e,n??t]))}}:cS(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function cS(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function lS(e,t,n,r){if(e.kind===`segment`&&By(e)===t){let{when:t,...i}=e;return{kind:`container`,direction:`horizontal`,children:r===`before`?[n,i]:[i,n],...t!==void 0&&{when:t}}}return e.kind===`container`?uS(e,t,n,r):dS(e,t,n,r)}function uS(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&By(e)===t);if(i>=0){let t=r===`before`?i:i+1,{when:a}=e.children[i];return{...e,children:[...e.children.slice(0,t),{...n,...a!==void 0&&{when:a}},...e.children.slice(t)]}}for(let[i,a]of e.children.entries()){let o=a.kind===`container`?uS(a,t,n,r):dS(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function dS(e,t,n,r){let i=!1,a=Uy(e,e=>{let a=uS(e,t,n,r);return i=a!==null,a??e});return i?a:null}function fS(e){if(!eS(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const pS=`default`,mS={};function hS(e){return[...new Set([pS,...Object.keys(e)])]}function gS(e,t,n){return oy(void 0,e,t,pS,n)}function _S(e,t){let n={[pS]:mS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${pS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function vS(e,t){let n=_S(e.presets,t).root??$x;return{node:rS(oS(n,e.root)),path:fS(n)?`presets.${t}.root`:`root`}}function yS(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=sS(e.root,t),i=Object.entries(e.presets).filter(([,e])=>fS(e.root??$x)).map(([n,r])=>({name:n,preset:r,...sS(oS(r.root??$x,e.root),t)})),a=new Map,o=e=>({cell:t,reason:n})=>{let r=a.get(t)??new Map;r.set(n,[...r.get(n)??[],e]),a.set(t,r)};(n.root?r.unplaced:[]).forEach(o(`the root`));for(let{name:e,unplaced:t}of i.filter(({name:e})=>n.presets.has(e)))t.forEach(o(`preset "${e}"`));return{config:{...e,root:r.root,presets:{...e.presets,...Object.fromEntries(i.map(({name:e,preset:t,root:n})=>[e,{...t,root:rS(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>bS(e,`${t} (in ${n.join(`, `)})`)))}}function bS(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function xS(e,t){return{...e.globals,..._S(e.presets,t).globals}}const SS=new Map;function CS(e,t,n={}){SS.set(e,{permanent:!0,resolve:t,...n})}CS(`themes`,()=>ny(),{paletteOf:e=>Hx(e)});const wS=`placementThemes`;CS(wS,ry,{paletteOf:(e,t)=>Ux(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of Kee)CS(e,()=>t,{library:n,labelOf:r});function qee(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Gx(n.basePalette,e.styles[t])}],[`presets`,{members:hS(e.presets)}]])}function TS(e){return[...new Set([...SS.keys(),...e.keys()])]}function ES(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=SS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(DS(e,t))}const Jee=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function DS(e,t){let n=Jee.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${TS(t).join(`, `)})`}function OS(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function kS(e){return e}function AS(e,t,n){return n===void 0?Mi+OS(e)+`.`+OS(t):jS(n)}function jS(e){return Mi+OS(e)}function MS(e,t){return e+`.`+t}function NS(e){return Ni+e}const PS=[`closeOnPick`,`paged`,`key`,`distribution`],FS=e=>PS.includes(e),IS=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${uv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function LS(e){for(let t of Object.keys(e))if(!FS(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${IS}`);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&&!dv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${uv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:pv(r)}}const RS=e=>`from`in e?e.from:e.themes;function zS(e,t,n){return e===`bool`?Iy(t)!==null:`min`in e?Ly(t,e)!==null:ES(RS(e),n).members.includes(t)}function BS(e,t){if(e===`bool`)return Py.join(` or `);if(!(`min`in e)){let n=RS(e),{members:r}=ES(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 VS(e){return{label:e.label,domain:HS(e.domain)}}function HS(e){return e===`theme`?{themes:wS}:e===`bool`||`min`in e?e:{from:e}}function US(e,t,n,r,i){let a=xi(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Py]}},variables:{}};if(`from`in o)return WS(t,r,i,o.from,e=>({template:`{{ carousel "${e.apply}" "${e.open}" "${a}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return WS(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 WS(e,t,n,r,i){let a={variable:n,key:n,member:t},o=MS(n,t),s=`${t}.open`,c=NS(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]:ki(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Oi(n,gi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const GS=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],KS=Object.fromEntries(GS.map(e=>[e.member,e.label])),qS={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},JS=Object.keys(qS),YS=zx(e=>Mx[e].place),XS=e=>Object.hasOwn(qS,e),ZS=(e,t)=>e===t||XS(e)&&ZS(YS[qS[e].beside],t),QS=e=>XS(e)?`${QS(YS[qS[e].beside])} › ${qS[e].trigger}`:e===`door`?`first line`:KS[e],$S=e=>QS(YS[e]),eC=()=>[`door`,...GS.map(e=>e.member)].flatMap(e=>[e,...JS.filter(t=>ZS(t,e))]).map(e=>({path:QS(e),names:Nx.filter(t=>YS[t]===e)})).filter(({names:e})=>e.length>0),tC=e=>{let{setting:t,on:n,inTmux:r}=Ub[e].switch;return`${Ub[e].label} is off — turn it on in the settings menu's ${$S(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},nC=Object.fromEntries(Object.entries(Cx).map(([e,t])=>[e,t.spec]));function rC(e){return iC(Cx[e])}function iC(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function aC(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:q(e.source,[...n.split(`.`),r])})}}}function oC(e){return aC(`${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 sC(e){return aC(`${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 cC(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&cy(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:q(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const lC={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)`,experimentalTmuxStatus:`it became the renderer setting — write renderer: "tmux" (or pick tmux in ${$S(`renderer`)} › renderer, from a session inside tmux)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},uC={noun:`globals key`,fields:nC,removed:lC},dC={preset:oC(`a preset`),menuGlyph:sC(`a preset`)},fC={noun:`preset globals key`,fields:{...nC,...dC},removed:lC};function pC(e){return CC(e)&&!(e in dC)}const mC=`is decided later than any rule could be settled`,hC={noun:`editGlobals key`,removed:lC,fields:{...nC,preset:oC(`the editGlobals fragment`),menuGlyph:sC(`the editGlobals fragment`),palette:cC(nC.palette,`the editGlobals fragment`,mC),style:cC(nC.style,`the editGlobals fragment`,mC),effect:cC(nC.effect,`the editGlobals fragment`,mC)}},gC={noun:`theme default key`,fields:{...Object.fromEntries(Ex.map(e=>[e,nC[e]])),style:cC(nC.style,`a theme's default`,`is the look that theme wears by name`)}};function _C(e,t){if(!bb(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${xb(t)}`,line:q(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${$v(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[`themeDefaults`,r])});continue}let a=Sb(e,gC,t,i);a!==null&&(n[r]=a)}return n}function vC(e,t,n){return n===void 0?{}:Sb(e,uC,t,n)??{}}function yC(e,t,n){return Sb(e,fC,t,n)??{}}function bC(){return Lb(fC)}function xC(e,t,n){return Sb(e,hC,t,n)??{}}const SC=new Set(Object.keys(nC));function CC(e){return SC.has(e)}function wC(e){return Object.hasOwn(lC,e)?lC[e]:void 0}function TC(){return[...SC]}const EC=new Map(Object.entries(Cx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function DC(e){let t=new Map;for(let[n,r]of EC){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const OC=/^segments\.([^.]+)\.palette$/,kC=/^presets\.(.+)\.root$/,AC=/^presets\.(.+)\.globals\.([^.]+)$/,jC=/^themeDefaults\.(.+)\.([^.]+)$/;function MC(e){return`presets.${e}.root`}function NC(e,t){return`themeDefaults.${e}.${t}`}const PC=e=>Ex.includes(e);function FC(e,t){return`presets.${e}.globals.${t}`}function IC(e){if(CC(e))return{scope:`globals`,field:e};let t=OC.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=AC.exec(e);if(n&&pC(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=jC.exec(e);if(r&&PC(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=kC.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function LC(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 RC=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],zC=[...RC,`other`],BC={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`};var VC=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?XC(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}},HC=class extends VC{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},UC=class extends VC{name=`EvalError`;kind=`EvalError`},WC=class extends UC{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=ZC(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}},GC=class extends UC{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}},KC=class extends UC{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}},qC=class extends KC{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)}`}},JC=class extends UC{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},YC=class extends UC{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function XC(e,t){let n=e.split(`
|
|
56
|
+
`)}},jee=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
|
|
57
|
+
`)),this.errors=e,this.name=`DroppedPlacements`}};function q(e,t){return pb(e)(t)}function pb(e){let t,n=()=>(t??={node:Mee(e)},t.node);return t=>Nee(e,n,t)}function Mee(e){try{return Ua(e)}catch(e){if(e instanceof La)return;throw e}}function Nee(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?Pee(e,t(),n):void 0;if(r!==void 0)return r;let i=0,a;for(let t of n){if(t===``||/^\d+$/.test(t))continue;let n=Fee(e,i,t);if(n===-1)return a===void 0?void 0:mb(e,a);i=n,a=n}return a===void 0?void 0:mb(e,a)}function Pee(e,t,n){if(t===void 0)return;let r=t,i,a=!1;for(let e of n){let t=r.kind===`array`&&/^\d+$/.test(e),n=r.kind===`array`?t?r.elements[Number(e)]:void 0:Wa(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:mb(e,i.span.start)}function Fee(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 mb(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Iee(e,t){try{return Ua(t),null}catch(n){if(!(n instanceof La))throw n;return`${e}:${mb(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Lee(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(`
|
|
58
|
+
`)}function hb(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 ${bb(i)}`,line:q(e.source,[...t.split(`.`),r])}),null)}function Ree(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 ${bb(i)}`,line:q(e.source,[...t.split(`.`),`default`])});return}return i}}function gb(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 ${bb(i)}`,line:q(e.source,[...t.split(`.`),r])});return}return i}}function _b(e,t,n){let r=gb(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Qv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[...t.split(`.`),`palette`])});return}return r}}function vb(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 ${J(a)}`,line:q(e.source,[...t.split(`.`),r])});return}return a}}function yb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bb(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function J(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function xb(e,t,n,r){return yb(r)?(wb(e,n,r,t.noun,new Set(Object.keys(t.fields)),Sb(e,t.removed??{},n,r)),Cb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${bb(r)}`,line:q(e.source,n.split(`.`))}),null)}function Sb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Tb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Cb(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 zee=new Set;function wb(e,t,n,r,i,a=zee){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:q(e.source,[...t.split(`.`),o])})}function Tb(e,t,n){return e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))}),null}function Eb(e,t,n,r){if(!yb(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${bb(r)}`,line:q(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:q(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:q(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:q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Bee(e,t,n,r){if(!yb(r))return e.issues.push({path:n,message:`${n} must be an object, got ${bb(r)}`,line:q(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 ${bb(i)}`,line:q(e.source,n.split(`.`))}),null;let a=t.arms;if(!Object.hasOwn(a,i)){let o=Object.hasOwn(t.retired,i)?t.retired[i](r):`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`;return e.issues.push({path:`${n}.${t.tag}`,message:o,line:q(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 wb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Vee(e,t,n){return{json:Lb(Fb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Db(e){return(...t)=>e()(...t)}function Hee(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:q(n.source,o.split(`.`))}),null}return a}}function Ob(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>gb(e,t,r,n)}}function kb(){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 ${bb(i)}`,line:q(e.source,[n])});return}return i}}}}function Uee(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 ${J(o)}`,line:q(e.source,[i])});return}return o}}}}function Ab(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 ${J(a)}`,line:q(e.source,[r])});return}return a}}}}function Wee(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>_b(e,t,r)}}function jb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>hb(e,t,r,n)??void 0}}function Mb(e,t){return re(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Nb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=hb(e,t,r,n);if(i===null)return;let a=Mb(`${t}.${n}`,i);return a===null?i:Tb(e,`${t}.${n}`,a)??void 0}}}function Pb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>vb(t,n,i,r,e)}}function Fb(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 Ib(e){return Fb(e.fields)}function Lb(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Rb(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function zb(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const Bb=[`claude`,`tmux`],Vb=`ne .tmux.pane ""`,Hb={band:{switch:{setting:`experimentalBand`,on:!0,inTmux:!1},label:`🧪 band (A)`,handsOff:!0,rows:null},statusline:{switch:{setting:`experimentalStatusline`,on:!0,inTmux:!1},label:`🧪 statusline (B)`,handsOff:!1,rows:null},pane:{switch:{setting:`experimentalPane`,on:!0,inTmux:!1},label:`🧪 tmux pane (C)`,handsOff:!0,rows:null},tmuxStatus:{switch:{setting:`renderer`,on:`tmux`,inTmux:!0},label:`tmux status line`,handsOff:!0,rows:5}},Ub=Object.keys(Hb),Wb=Ub.filter(e=>Hb[e].switch.on===!0),Gb={by:`request`},Kb=e=>`drawing.${e}`,qb={subscribers:0,fps:0,shown:!0},Jb=(e,t)=>`feeds.${e}.${t}`;function Yb(e){return Object.fromEntries(Ub.map(t=>[t,e(t)]))}const Gee=Yb(()=>qb);function Xb(e){return typeof e==`string`&&Object.hasOwn(Hb,e)?e:null}const Zb=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),Qb=[...Zb(3,1),...Zb(3,.25)],$b=Qb.reduce((e,{seconds:t})=>e+t,0),ex={min:15,max:600,step:15},tx=(e,t)=>e+t,nx=e=>e-$b,rx=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),ix=(e,t,n={})=>({spec:Pb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),ax=e=>t=>e.includes(t)?`🧪 ${t}`:t,ox={spec:kb(),domain:`bool`,parse:Fy},sx=e=>({spec:Uee(e),domain:e,parse:t=>Iy(t,e)});function cx(e,t,n,r={}){return{kind:`session`,...ix(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function lx(e,t){return{kind:`session`,...ox,floor:e,control:t,themeDefault:!1}}function ux(e,t,n){return{kind:`session`,...sx(e),floor:t,control:n,themeDefault:!1}}function dx(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const fx=e=>({kind:`text`,spec:e}),px={required:!1,json:{enum:[...Ey]},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: ${Ey.join(`, `)}`,line:q(e.source,[...t.split(`.`),n])});return}return vb(e,t,r,n,Ey)}},mx={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=gb(e,t,r,n);return sy(i)?i:_b(e,t,r)}},hx={required:!1,json:{anyOf:[{enum:[...gy]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&sy(i)?i:vb(e,t,r,n,gy)}},gx=/^[^\r\n]*\S[^\r\n]*$/u,_x=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),vx={required:!1,json:{type:`string`,pattern:gx.source,not:{pattern:_x.source}},parse:(e,t,n,r)=>{let i=gb(e,t,r,n);if(i===void 0||gx.test(i)&&!_x.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:q(e.source,[...t.split(`.`),n])})}},yx=Object.fromEntries(Wb.map(e=>[Hb[e].switch.setting,lx(!1,rx(Hb[e].label,`toggles`))])),bx={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},xx={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:bx[e]})},Sx={palette:dx(`theme`,mx,{themes:`themes`},rx(`🎨 theme`,`door`)),preset:dx(`preset`,Ob(),{from:`presets`},rx(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:dx(`style`,Ob(),{from:`styles`},rx(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:dx(`effect`,hx,{from:gy},rx(`✨ effect`,`look`)),endcaps:cx(Cy,`powerline`,rx(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:cx(ky,`accent`,rx(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:ax(Q_),themeDefault:!0}),shade:cx(Ay,`middle`,rx(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:ax(V_),themeDefault:!0}),transitions:lx(!1,rx(`fade in/out`,`look`)),animationSpeed:cx(vy,`1x`,rx(`speed`,`look`)),autoWrap:lx(!0,rx(`wrap`,`config`)),padding:ux({...Py,step:1},1,rx(`padding`,`config`)),updateNotice:lx(!0,rx(`update notice`,`config`)),menuTimeout:ux(ex,120,rx(`menu timeout`,`config`)),renderer:cx(Bb,`claude`,rx(`renderer`,`config`,{shown:Vb}),{optionDomain:`renderers`,library:xx}),...yx,colorCompatibility:{kind:`config`,...ix(Ey,`colorCompatibilities`),spec:px,floor:`truecolor`},default_empty_value:fx(Ob()),default_separator:fx(Ob()),menuGlyph:fx(vx)},Cx=Object.entries(Sx),wx=Cx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Kee=Cx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Tx=Cx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),qee=Cx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Ex(e){return Sx[e]}const Dx=e=>Ex(e).floor;function Ox(e){let t=Sx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const kx=e=>`${e}.effective`,Ax=e=>{let t=Sx[e];return t.kind===`selection`?t.sessionKey:e},jx=Object.fromEntries(Kee.map(e=>{let t=Ax(e);return[t,{configKey:e,sessionKey:t,effectiveVar:kx(t),...Sx[e].control}]})),Mx=Object.keys(jx),Nx=Object.values(jx),Px=wx.filter(e=>Sx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:kx(e)})),Fx=new Set(Px.map(e=>e.configKey)),Ix=new Map([...Nx,...Px].map(e=>[e.configKey,e.effectiveVar])),Lx=new Map(Nx.map(e=>[e.sessionKey,e.effectiveVar]));function Rx(e){return Object.fromEntries(Mx.map(t=>[t,e(t)]))}const zx=new Map(Mx.map(e=>[jx[e].sessionKey,e])),Bx=new Map;function Vx(e){let t=Ux(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 Hx(e,t){return e===`bar`?t:Vx(e)}function Ux(e){let t=Bx.get(e);if(t!==void 0)return t;let n=Ed(e);return n===null?null:(Bx.set(e,n),n)}function Wx(e,t){return Gx(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Rd(e,t))}const Gx=D_();function Kx(e){let t=Ux(e);return t===null?null:{kind:`decided`,name:e,value:t}}function qx(e,t,n){let r=Kx(e);return r===null?(n(hy(t,`palette`,`"${e}" names no installed theme${Qv(e)}`)),Yx()):r}function Jx(e,t,n){return cy(e,t,n,Yx(),Kx)}function Yx(){return{kind:`decided`,name:$v,value:Vx($v)}}const Xx=/^[A-Za-z_][A-Za-z0-9_]*$/;function Zx(e){return`#${e+1}`}const Qx={rows:{}};function $x(e){return`rows`in e}function eS(e){return Object.fromEntries(e.map((e,t)=>[Zx(t),e]))}function tS(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:eS(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:eS([n])}}function nS(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function rS(e){return $x(e)?nS(e):e}function*iS(e,t){if(!$x(e)){yield*Ky(e,t);return}yield[nS(e),t];for(let[n,r]of Object.entries(e.rows))yield*Ky(r,`${t}.rows.${n}`)}function aS(e,t){return $x(e)?{...t,...e,rows:{...t.rows,...e.rows}}:tS(e)}function oS(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...Uy(nS(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||zy(e)===t.id)))return e;let i=r.find(e=>zy(e)===n);if(i!==void 0)return sS(e,t,`as "${n}", but placement "${n}" is already segment "${i.name}" — give the cell its own id`);let a={kind:`segment`,name:t.seg,...t.id!==void 0&&{id:t.id},insertedBy:t.by},o=Object.entries(e.root.rows).map(([e,n])=>[e,n,cS(n,t.anchor,a,t.relation)]);return o.some(([,,e])=>e!==null)?{...e,root:{...e.root,rows:Object.fromEntries(o.map(([e,t,n])=>[e,n??t]))}}:sS(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function sS(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function cS(e,t,n,r){if(e.kind===`segment`&&zy(e)===t){let{when:t,...i}=e;return{kind:`container`,direction:`horizontal`,children:r===`before`?[n,i]:[i,n],...t!==void 0&&{when:t}}}return e.kind===`container`?lS(e,t,n,r):uS(e,t,n,r)}function lS(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&zy(e)===t);if(i>=0){let t=r===`before`?i:i+1,{when:a}=e.children[i];return{...e,children:[...e.children.slice(0,t),{...n,...a!==void 0&&{when:a}},...e.children.slice(t)]}}for(let[i,a]of e.children.entries()){let o=a.kind===`container`?lS(a,t,n,r):uS(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function uS(e,t,n,r){let i=!1,a=Hy(e,e=>{let a=lS(e,t,n,r);return i=a!==null,a??e});return i?a:null}function dS(e){if(!$x(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const fS=`default`,pS={};function mS(e){return[...new Set([fS,...Object.keys(e)])]}function hS(e,t,n){return ay(void 0,e,t,fS,n)}function gS(e,t){let n={[fS]:pS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${fS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function _S(e,t){let n=gS(e.presets,t).root??Qx;return{node:nS(aS(n,e.root)),path:dS(n)?`presets.${t}.root`:`root`}}function vS(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=oS(e.root,t),i=Object.entries(e.presets).filter(([,e])=>dS(e.root??Qx)).map(([n,r])=>({name:n,preset:r,...oS(aS(r.root??Qx,e.root),t)})),a=new Map,o=e=>({cell:t,reason:n})=>{let r=a.get(t)??new Map;r.set(n,[...r.get(n)??[],e]),a.set(t,r)};(n.root?r.unplaced:[]).forEach(o(`the root`));for(let{name:e,unplaced:t}of i.filter(({name:e})=>n.presets.has(e)))t.forEach(o(`preset "${e}"`));return{config:{...e,root:r.root,presets:{...e.presets,...Object.fromEntries(i.map(({name:e,preset:t,root:n})=>[e,{...t,root:nS(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>yS(e,`${t} (in ${n.join(`, `)})`)))}}function yS(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function bS(e,t){return{...e.globals,...gS(e.presets,t).globals}}const xS=new Map;function SS(e,t,n={}){xS.set(e,{permanent:!0,resolve:t,...n})}SS(`themes`,()=>ty(),{paletteOf:e=>Vx(e)});const CS=`placementThemes`;SS(CS,ny,{paletteOf:(e,t)=>Hx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of qee)SS(e,()=>t,{library:n,labelOf:r});function Jee(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Wx(n.basePalette,e.styles[t])}],[`presets`,{members:mS(e.presets)}]])}function wS(e){return[...new Set([...xS.keys(),...e.keys()])]}function TS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=xS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(ES(e,t))}const Yee=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function ES(e,t){let n=Yee.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${wS(t).join(`, `)})`}function DS(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function OS(e){return e}function kS(e,t,n){return n===void 0?Mi+DS(e)+`.`+DS(t):AS(n)}function AS(e){return Mi+DS(e)}function jS(e,t){return e+`.`+t}function MS(e){return Ni+e}const NS=[`closeOnPick`,`paged`,`key`,`distribution`],PS=e=>NS.includes(e),FS=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${uv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function IS(e){for(let t of Object.keys(e))if(!PS(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${FS}`);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&&!dv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${uv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:pv(r)}}const LS=e=>`from`in e?e.from:e.themes;function RS(e,t,n){return e===`bool`?Fy(t)!==null:`min`in e?Iy(t,e)!==null:TS(LS(e),n).members.includes(t)}function zS(e,t){if(e===`bool`)return Ny.join(` or `);if(!(`min`in e)){let n=LS(e),{members:r}=TS(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 BS(e){return{label:e.label,domain:VS(e.domain)}}function VS(e){return e===`theme`?{themes:CS}:e===`bool`||`min`in e?e:{from:e}}function HS(e,t,n,r,i){let a=xi(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Ny]}},variables:{}};if(`from`in o)return US(t,r,i,o.from,e=>({template:`{{ carousel "${e.apply}" "${e.open}" "${a}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return US(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 US(e,t,n,r,i){let a={variable:n,key:n,member:t},o=jS(n,t),s=`${t}.open`,c=MS(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]:ki(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Oi(n,gi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const WS=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],GS=Object.fromEntries(WS.map(e=>[e.member,e.label])),KS={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},qS=Object.keys(KS),JS=Rx(e=>jx[e].place),YS=e=>Object.hasOwn(KS,e),XS=(e,t)=>e===t||YS(e)&&XS(JS[KS[e].beside],t),ZS=e=>YS(e)?`${ZS(JS[KS[e].beside])} › ${KS[e].trigger}`:e===`door`?`first line`:GS[e],QS=e=>ZS(JS[e]),$S=()=>[`door`,...WS.map(e=>e.member)].flatMap(e=>[e,...qS.filter(t=>XS(t,e))]).map(e=>({path:ZS(e),names:Mx.filter(t=>JS[t]===e)})).filter(({names:e})=>e.length>0),eC=e=>{let{setting:t,on:n,inTmux:r}=Hb[e].switch;return`${Hb[e].label} is off — turn it on in the settings menu's ${QS(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},tC=Object.fromEntries(Object.entries(Sx).map(([e,t])=>[e,t.spec]));function nC(e){return rC(Sx[e])}function rC(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function iC(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:q(e.source,[...n.split(`.`),r])})}}}function aC(e){return iC(`${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 oC(e){return iC(`${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 sC(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&sy(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:q(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const cC={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)`,experimentalTmuxStatus:`it became the renderer setting — write renderer: "tmux" (or pick tmux in ${QS(`renderer`)} › renderer, from a session inside tmux)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},lC={noun:`globals key`,fields:tC,removed:cC},uC={preset:aC(`a preset`),menuGlyph:oC(`a preset`)},dC={noun:`preset globals key`,fields:{...tC,...uC},removed:cC};function fC(e){return SC(e)&&!(e in uC)}const pC=`is decided later than any rule could be settled`,mC={noun:`editGlobals key`,removed:cC,fields:{...tC,preset:aC(`the editGlobals fragment`),menuGlyph:oC(`the editGlobals fragment`),palette:sC(tC.palette,`the editGlobals fragment`,pC),style:sC(tC.style,`the editGlobals fragment`,pC),effect:sC(tC.effect,`the editGlobals fragment`,pC)}},hC={noun:`theme default key`,fields:{...Object.fromEntries(Tx.map(e=>[e,tC[e]])),style:sC(tC.style,`a theme's default`,`is the look that theme wears by name`)}};function gC(e,t){if(!yb(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${bb(t)}`,line:q(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${Qv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[`themeDefaults`,r])});continue}let a=xb(e,hC,t,i);a!==null&&(n[r]=a)}return n}function _C(e,t,n){return n===void 0?{}:xb(e,lC,t,n)??{}}function vC(e,t,n){return xb(e,dC,t,n)??{}}function yC(){return Ib(dC)}function bC(e,t,n){return xb(e,mC,t,n)??{}}const xC=new Set(Object.keys(tC));function SC(e){return xC.has(e)}function CC(e){return Object.hasOwn(cC,e)?cC[e]:void 0}function wC(){return[...xC]}const TC=new Map(Object.entries(Sx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function EC(e){let t=new Map;for(let[n,r]of TC){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const DC=/^segments\.([^.]+)\.palette$/,OC=/^presets\.(.+)\.root$/,kC=/^presets\.(.+)\.globals\.([^.]+)$/,AC=/^themeDefaults\.(.+)\.([^.]+)$/;function jC(e){return`presets.${e}.root`}function MC(e,t){return`themeDefaults.${e}.${t}`}const NC=e=>Tx.includes(e);function PC(e,t){return`presets.${e}.globals.${t}`}function FC(e){if(SC(e))return{scope:`globals`,field:e};let t=DC.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=kC.exec(e);if(n&&fC(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=AC.exec(e);if(r&&NC(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=OC.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function IC(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 LC=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],RC=[...LC,`other`],zC={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`};var BC=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?YC(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}},VC=class extends BC{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},HC=class extends BC{name=`EvalError`;kind=`EvalError`},UC=class extends HC{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=XC(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}},WC=class extends HC{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}},GC=class extends HC{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}},KC=class extends GC{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)}`}},qC=class extends HC{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},JC=class extends HC{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function YC(e,t){let n=e.split(`
|
|
59
59
|
`),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(`
|
|
60
|
-
`)}function
|
|
60
|
+
`)}function XC(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:ZC(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 ZC(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 QC(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const $C=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`]]),ew={left:`{{`,right:`}}`};var tw=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=ew){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 VC(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&&nw(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);nw(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);nw(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(;nw(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`;nw(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&&(iw(e)||rw(e)&&iw(this.src[this.offset+1]??``)||e===`.`&&iw(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&lw(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===`
|
|
61
61
|
`)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===`
|
|
62
|
-
`)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(
|
|
62
|
+
`)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(rw(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);aw(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);ow(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);sw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;iw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);iw(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),rw(this.src[this.offset]??``)&&this.advanceBy(1);iw(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return aw(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);uw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&lw(this.src[this.offset+1]??``);)for(this.advanceBy(1);uw(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),!lw(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;uw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&lw(this.src[this.offset+1]??``);)for(this.advanceBy(1);uw(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(;uw(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=$C.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===`
|
|
63
63
|
`)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
|
|
64
|
-
`?(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
|
|
65
|
-
`}function
|
|
66
|
-
`;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 HC(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Ow(e,t,n){let r=Dw(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new HC(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function kw(e,t){if(t(e)!==!1)for(let n of Aw(e))kw(n,t)}function Aw(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 $C(e)}}const jw=Symbol(`go-template-js.MISSING`);function Mw(e,t){if(e==null)return jw;if(e instanceof Map)return e.has(t)?e.get(t):jw;if(Array.isArray(e))return jw;if(typeof e==`object`){let n=e;return t in n?n[t]:jw}return jw}function Nw(e,t){let n=e;for(let e of t){if(n===jw)return jw;n=Mw(n,e)}return n}function Pw(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)=>Pw(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)||!Pw(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=>Pw(e[n],t[n])):!1}return!1}const Fw=new WeakSet;function Iw(e){return Fw.add(e),e}function Lw(e){return Fw.has(e)}function Rw(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 zw(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Hw(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Hw(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Uw(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Uw(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Uw(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Uw(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Ww(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Gw(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>qw(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Xw(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Xw(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>aT(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>cT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>cT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>$w(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>nT(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>iT(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Rw(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Bw(){return{and:Iw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Rw(t))return t;return t}}),or:Iw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Rw(t))return t;return t}})}}function Vw(e,t){return{...zw(e,t),...Bw()}}function Hw(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Pw(e,t)}function Uw(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 Ww(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Gw(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Kw(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 ${Jw(t)}`);return e[t]}throw Error(`index: cannot index ${Jw(e)}`)}function Kw(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 ${Yw(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function qw(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]=Kw(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 Jw(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Yw(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 Xw(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+=Zw(a,t),r=o}return n}function Zw(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Qw={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function $w(e){return e.replace(/[\0"'&<>]/g,e=>Qw[e]??e)}const eT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},tT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function nT(e){let t=``;for(let n of e){let e=eT[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!tT.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const rT=new TextEncoder;function iT(e){let t=``,n=rT.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 aT(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+=oT(l??``,u,d,n,r),o=c+1}return i}function oT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?sT(t,n):sT(t,Zw(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Yw(n)}=${Zw(n,r)})`:sT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return sT(t,cT(n,r,i));case`q`:return sT(t,JSON.stringify(Zw(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Yw(n)}=${Zw(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return sT(t,Number(n).toFixed(i))}case`t`:return sT(t,Rw(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 sT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Yw(n)}=${Zw(n,r)})`:typeof n==`bigint`?sT(t,n.toString(16)):sT(t,Math.trunc(n).toString(16));default:return`%!${e}(${Yw(n)}=${Zw(n,r)})`}}function sT(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 cT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>cT(e,t,n)).join(` `)}]`:e instanceof Map?lT([...e.entries()],t,n):uT(e)?lT(Object.entries(e),t,n):String(e)}function lT(e,t,n){let r=e=>cT(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 uT(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 dT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function fT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function pT(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 mT(e,t,n){e.vars.set(t,n)}const hT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],gT=new Set([`default`,`zero`,`error`]);function _T(e){if(e===void 0)return`default`;if(gT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${vT(e)}`)}function vT(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 yT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${vT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${vT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${vT(e.right)}`);return{left:e.left,right:e.right}}}function bT(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function xT(e){let t=new Set(hT);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 ${hT.join(`, `)}`)}),bT(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 ST=Object.freeze({kind:`break`}),CT=Object.freeze({kind:`continue`}),Xee={kind:`none`};let wT;(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{wT=(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 Zee(e){let t=new Set,n=e=>{kw(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 TT={kind:`dynamic`};function ET(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=PT(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:TT}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return TT;let t=e.cmds[0];if(t===void 0)return TT;let n=t.args[0];return n===void 0||n.type!==`Identifier`?TT:{kind:`call`,name:n.ident,args:t.args.slice(1).map(ET)}}default:return TT}}function Qee(e){let t=[],n=e=>{kw(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(ET);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 $ee=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??kT,this.isT=e.isT??DT,this.missingKey=_T(e.missingKey),this.delims=yT(e.delims),this.funcs=xT({...Vw(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=gw(e,this.delims,t);return wT(n.source,e=>this.evalParsed(n,e),n.defines,Zee(n),Qee(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=dT(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 ST;case`Continue`:throw CT;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 UC(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:$C(e)}}evalIf(e,t,n){Rw(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(Rw(r)){let i=fT(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=lte(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=fT(t,o);if(i.length===1)mT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;mT(a,e,r),mT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===CT)continue;throw e}}}catch(e){if(e===ST)return;throw e}}evalTemplateInvoke(e,t,n){let r=mw(n.defines,e.name);if(!r)throw new UC(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=fT(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=fT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=mw(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 UC(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Xee);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)mT(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 UC(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new UC(`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 WC(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Lw(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){ete(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof KC?new KC(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof YC?new YC(t.message,r,{source:i.source}):t instanceof VC?t:new UC(`error calling ${e}: ${cte(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 PT(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 WC(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 UC(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Nw(e,t);if(i!==jw)return i;if(this.missingKey===`error`)throw new JC(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=pT(t,i);if(!a.found)throw new UC(`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(cT(e,this.toString,this.isT)))}};const DT=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function OT(e){return new $ee(e)}function ete(e,t,n,r,i,a=kT,o=ite,s=DT){let{argTypes:c,arity:l}=t,u=tte(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new GC(e,u,n.length,r,{source:i});let d=nte(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!rte(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new qC(e,t+1,l,r,{source:i}):new KC(e,t+1,jT(c),MT(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(!ote(n[f],l))throw new KC(e,t+1,`${jT(`ordered`)} of the same kind as ${MT(n[f])}`,MT(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!ste(n[p],l))throw new KC(e,t+1,`${jT(`comparable`)} of the same kind as ${MT(n[p])}`,MT(l),r,{source:i})}}}function tte(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 nte(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 rte(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 uT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||uT(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||uT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||uT(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 ate(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function ite(e){return e}function kT(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 KC(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,MT(e),{line:0,column:0,offset:0})}function ate(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function ote(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function ste(e,t){let n=AT(e),r=AT(t);return n===`nil`||r===`nil`?!0:n===r}function AT(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 jT(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 cte(e){return e instanceof Error?e.message:String(e)}function MT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function lte(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?NT([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?NT(Object.entries(e)):[]}function NT(e){return[...e].sort((e,t)=>ute(e[0],t[0]))}function ute(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 PT(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 dte(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function fte(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 FT(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 pte(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=FT(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 mte(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=FT(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 hte(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 gte(e){return JSON.stringify(e)??`null`}function IT(){return{atoi:{fn:e=>dte(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>pte(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>mte(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>fte(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>hte(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>gte(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const LT={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function RT(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*LT[a],n=n.slice(e[0].length)}return t?-r:r}function zT(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<LT.us?`${Math.floor(n)}ns`:n<LT.ms?BT(n,LT.us,3,`µs`):n<LT.s?BT(n,LT.ms,6,`ms`):VT(n),t?`-${r}`:r}function BT(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 VT(e){let t=Math.floor(e/LT.h);e-=t*LT.h;let n=Math.floor(e/LT.m);e-=n*LT.m;let r=Math.floor(e/LT.s),i=e-r*LT.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 HT(e){return e*LT.s}function UT(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 WT(e,t){let n=t().getTime()-UT(e).getTime();return zT(Math.round(n/1e3)*1e9)}const GT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],KT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],qT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],JT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function YT(e){return e<10?`0${e}`:String(e)}function XT(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function ZT(e){return e<10?` ${e}`:String(e)}function QT(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${YT(Math.floor(n/60))}${YT(n%60)}`}function $T(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${YT(Math.floor(n/60))}:${YT(n%60)}`}function eE(e){return`${e>=0?`+`:`-`}${YT(Math.floor(Math.abs(e)/60))}`}function tE(e){return e===0?`Z`:QT(e)}function nE(e){return e===0?`Z`:$T(e)}function rE(e){return e===0?`Z`:eE(e)}function iE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const aE=[[`.000000000`,e=>`.${iE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=iE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${iE(e.ms,6,!1)}`],[`.999999`,e=>{let t=iE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${XT(e.ms)}`],[`.999`,e=>{let t=XT(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>GT[e.month-1]??`January`],[`Monday`,e=>qT[e.weekday]??`Monday`],[`Z07:00`,e=>nE(e.offsetMinutes)],[`-07:00`,e=>$T(e.offsetMinutes)],[`Z0700`,e=>tE(e.offsetMinutes)],[`-0700`,e=>QT(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>KT[e.month-1]??`Jan`],[`Mon`,e=>JT[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>eE(e.offsetMinutes)],[`Z07`,e=>rE(e.offsetMinutes)],[`15`,e=>YT(e.hour)],[`01`,e=>YT(e.month)],[`02`,e=>YT(e.day)],[`_2`,e=>ZT(e.day)],[`03`,e=>YT(e.hour12)],[`04`,e=>YT(e.minute)],[`05`,e=>YT(e.second)],[`06`,e=>YT(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 oE(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of aE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const sE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function cE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const lE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function uE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=cE(new Intl.DateTimeFormat(`en-US`,{...sE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=cE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=dE(cE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=lE.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 dE(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 fE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function pE(e,t){return oE(e,uE(UT(t),fE()))}function mE(e,t,n){return oE(e,uE(UT(t),n))}function hE(e,t){let n=UT(t),r=RT(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function gE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:zT(HT(t))}return typeof e==`bigint`?zT(HT(Number(e))):typeof e==`number`?zT(HT(e)):`0s`}const _E=36e11*24*365,vE=36e11*24*30,yE=36e11*24,bE=36e11,xE=6e10,SE=1e9;function CE(e){let t=RT(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>_E?`${Math.floor(n/_E)}y`:n>vE?`${Math.floor(n/vE)}mo`:n>yE?`${Math.floor(n/yE)}d`:n>bE?`${Math.floor(n/bE)}h`:n>xE?`${Math.floor(n/xE)}m`:n>SE?`${Math.floor(n/SE)}s`:`0s`}function wE(e){let t=uE(UT(e),fE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function TE(e,t){let n=uE(UT(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function EE(e){return e()}const DE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],OE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function kE(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function AE(e,t,n){return[e.slice(t,t+n),t+n]}function jE(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 ME(e,t){for(let[n,r]of DE.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function NE(e,t){for(let[n,r]of OE.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function PE(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 FE(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 IE(e,t){if(e[t]===` `){let[n,r]=jE(e,t+1,1,1);return[n,r]}return jE(e,t,1,2)}function LE(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]=jE(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=jE(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=jE(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function RE(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]=jE(e,t+1,2,2);return[n*r*60,i]}return LE(e,t,n)}function zE(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 BE(e,t,n){let[r,i]=AE(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function VE(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=ME(t,n);return i.month=e,[r,i]}case`Monday`:return[PE(t,n),i];case`Jan`:{let[e,r]=NE(t,n);return i.month=e,[r,i]}case`Mon`:return[FE(t,n),i];case`2006`:{let[e,r]=jE(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=jE(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=jE(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=jE(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=IE(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=jE(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=jE(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=jE(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=jE(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=jE(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=jE(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=jE(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=jE(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=jE(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[zE(t,n),i];case`-0700`:{let[e,r]=LE(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=LE(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]=jE(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=RE(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=RE(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=RE(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]=BE(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]=BE(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]=BE(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 HE=`.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 UE(e,t){let n=0,r=0,i=kE();for(;n<e.length;){let a=!1;for(let o of HE)if(e.startsWith(o,n)){let[e,s]=VE(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 WE(e,t){return UE(e,t)}function GE(e){return String(Math.floor(UT(e).getTime()/1e3))}function KE(e=()=>new Date){return{now:{fn:()=>EE(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>pE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>mE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>hE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>wE(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>TE(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>gE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>CE(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>WE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>WT(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>GE(e),argTypes:[`value`],arity:{kind:`exact`}}}}function qE(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 JE(...e){for(let t of e)if(!qE(t))return t}function YE(e,t){return qE(t)?e:t}function XE(e){return JSON.parse(e)}function ZE(e,t,n){return Rw(n)?e:t}function QE(e){return JSON.stringify(e)??`null`}function $E(e){return JSON.stringify(e,null,2)??`null`}function eD(){return{default:{fn:(e,t)=>YE(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>qE(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>JE(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>ZE(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>XE(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>QE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>$E(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function tD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function nD(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 tD(...t)}function rD(e,t){return e[t]}function iD(e,t){return t in e}function aD(e){return Object.keys(e)}function oD(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 sD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function cD(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 lD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function uD(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function dD(e,t,n){return e[t]=n,e}function fD(e,t){return delete e[t],e}function pD(e){return Object.values(e)}function mD(){return{dict:{fn:(...e)=>tD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>rD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>dD(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>fD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>aD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>pD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>uD(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>lD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>cD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>iD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>oD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>sD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function hD(e){throw new YC(e)}function gD(){return{fail:{fn:e=>hD(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 _D(...e){for(let t of e)if(qE(t))return!1;return!0}function vD(...e){for(let t of e)if(!qE(t))return!0;return!1}function yD(e,t){return[...e,t]}function bD(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 xD(e){return e.filter(e=>!qE(e))}function SD(...e){let t=[];for(let n of e)t.push(...n);return t}const CD={line:0,column:0,offset:0};function wD(e,t,n,r){return new KC(e,t,n,r,CD)}function TD(...e){if(e.length<3)throw wD(`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(!DD(t))throw wD(`dig`,e.length-1,`dict`,OD(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw wD(`dig`,e,`string`,OD(r[e]));return ED(t,n,r,e.length)}function ED(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(!DD(a))throw wD(`dig`,r-1,`dict at intermediate key`,OD(a));return ED(a,t,n.slice(1),r)}function DD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function OD(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function kD(e){return e[0]}function AD(e,t){return t.some(t=>Pw(t,e))}function jD(e){return e.slice(0,-1)}function MD(e){return e[e.length-1]}function ND(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function PD(...e){return e}function FD(e,t){return[t,...e]}function ID(e){return e.slice(1)}function LD(e){return[...e].reverse()}function RD(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function zD(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function BD(e){let t=[];for(let n of e)t.some(e=>Pw(e,n))||t.push(n);return t}function VD(e,...t){return e.filter(e=>!t.some(t=>Pw(t,e)))}function HD(){return{list:{fn:(...e)=>PD(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>kD(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>MD(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>ID(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>jD(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>ND(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>LD(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>BD(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>VD(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>AD(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>xD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>RD(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>SD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>bD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>FD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>yD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>zD(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>yD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>PD(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>TD(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>_D(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>vD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function UD(...e){return e.reduce((e,t)=>e+t,0)}function WD(e){return e+1}function GD(e){return e+1}function KD(...e){return e.reduce((e,t)=>e+t,0)}function qD(e){return Math.ceil(e)}function JD(e,t){return Math.trunc(e/t)}function YD(e,...t){return t.reduce((e,t)=>e/t,e)}function XD(e){return Math.floor(e)}function ZD(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function QD(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function $D(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function eO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function tO(e,t){return e%t}function nO(...e){return e.reduce((e,t)=>e*t,1)}function rO(...e){return e.reduce((e,t)=>e*t,1)}function iO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function aO(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 oO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),aO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return aO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:aO(n,i+t,r).join(` `)}default:return``}}function sO(e,t){return e-t}function cO(e,...t){return t.reduce((e,t)=>e-t,e)}function lO(e){return aO(0,e,e<0?-1:1)}function uO(){return{add:{fn:(...e)=>UD(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>sO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>nO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>JD(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>tO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>$D(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>ZD(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>XD(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>qD(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>iO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>KD(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>cO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>rO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>YD(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>WD(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>GD(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>QD(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>eO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>ZD(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>oO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>lO(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>aO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function dO(e){return Array.from(e)}function fO(e,t){return e===``?dO(t):t.split(e)}function pO(e,t){let n=dO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function mO(e,t,n){let r=dO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const hO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},gO=/^[-_\s]$/,_O=/^\p{P}$/u,vO=/^\p{L}$/u,yO=/^\p{Lu}$/u,bO=/^\p{N}$/u;function xO(e){return e!==void 0&&gO.test(e)}function SO(e){return e!==void 0&&vO.test(e)}function CO(e){return e!==void 0&&yO.test(e)}function wO(e){return e!==void 0&&bO.test(e)}function TO(e){return e!==void 0&&_O.test(e)}function EO(e,t){if(t>=e.length)return{word:{wt:hO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(xO(n)){for(;r<e.length&&xO(e[r]);)r++;return{word:{wt:hO.Connector,text:e.slice(t,r).join(``)},next:r}}if(TO(n)){for(;r<e.length&&TO(e[r]);)r++;return{word:{wt:hO.Punct,text:e.slice(t,r).join(``)},next:r}}if(CO(n)){if(r>=e.length)return{word:{wt:hO.UpperCase,text:n},next:r};if(CO(e[r])){let n=r;for(;n<e.length&&CO(e[n]);)n++;return n<e.length&&SO(e[n])?{word:{wt:hO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:hO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(SO(e[r])){let n=r+1;for(;n<e.length&&SO(e[n])&&!CO(e[n]);)n++;return{word:{wt:hO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:hO.UpperCase,text:n},next:r}}if(SO(n)){for(;r<e.length&&SO(e[r])&&!CO(e[r]);)r++;return{word:{wt:hO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(wO(n)){for(;r<e.length&&wO(e[r]);)r++;return{word:{wt:hO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!xO(e[r])&&!SO(e[r])&&!wO(e[r])&&!TO(e[r]);)r++;return{word:{wt:hO.Other,text:e.slice(t,r).join(``)},next:r}}function DO(e,t,n){if(t.wt!==hO.UpperCase&&t.wt!==hO.Connector){e.push(t.text);return}for(let r of t.text)xO(r)?e.push(n):CO(r)?e.push(r.toLowerCase()):e.push(r)}function OO(e,t){if(e.length===0)return``;let n=dO(e),r=[],{word:i,next:a}=EO(n,0);for(;a<n.length;){i.wt!==hO.Connector&&DO(r,i,t);let e=i,o=i;if({word:i,next:a}=EO(n,a),e.wt===hO.Number){for(;i.wt===hO.Alphabet||i.wt===hO.Number;)DO(r,i,t),{word:i,next:a}=EO(n,a);i.wt!==hO.Invalid&&i.wt!==hO.Punct&&i.wt!==hO.Connector&&r.push(t);continue}if(e.wt===hO.Connector){DO(r,o,t);continue}if(e.wt===hO.Punct)continue;if(i.wt!==hO.Number){i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=EO(n,a),i.wt!==hO.Alphabet){DO(r,s,t),i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t);continue}for(r.push(t),DO(r,s,t);i.wt===hO.Alphabet||i.wt===hO.Number;)DO(r,i,t),{word:i,next:a}=EO(n,a);i.wt!==hO.Invalid&&i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t)}return DO(r,i,t),r.join(``).toLowerCase()}function kO(e){if(e.length===0)return``;let t=dO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!xO(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++,xO(i)&&xO(e)){n.push(e);continue}xO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function AO(e){return kO(e)}function jO(...e){return e.join(` `)}function MO(e,t){return t.includes(e)}function NO(e,t){return t.startsWith(e)}function PO(e,t){return t.endsWith(e)}function FO(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
64
|
+
`?(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 nw(e){return e===` `||e===` `||e===`\r`||e===`
|
|
65
|
+
`}function rw(e){return e===`+`||e===`-`}function iw(e){return e>=`0`&&e<=`9`}function aw(e){return iw(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function ow(e){return e>=`0`&&e<=`7`}function sw(e){return e===`0`||e===`1`}function cw(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function lw(e){return cw(e)||e===`_`}function uw(e){return lw(e)||iw(e)}let dw,fw;function pw(e,t){return fw(e,t)}var mw=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{dw=(t,n)=>new e(t,n),fw=(e,t)=>e.#e.get(t)??(e.#t&&fw(e.#t,t))}has(e){return fw(this,e)!==void 0}};function hw(e,t,n=mw.EMPTY){return new gw(e,t,n).parseTemplate()}var gw=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new tw(e,t):new tw(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:yw(n)});return n}errAt(e,t,n={}){return new VC(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 ${yw(e)}`,{found:yw(e)})}return{root:e,defines:dw(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=vw(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 _w(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${yw(n)} at top level`,{found:yw(n)})}return _w(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 VC(`{{${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 VC(`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:yw(e)});return Dw(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(!bw(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:yw(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=[xw(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(xw(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;bw(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 xw(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Dw(e.value,e.pos,this.source)};case`Number`:return Cw(e);case`Char`:return ww(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 ${yw(e)}`,{expected:`command argument`,found:yw(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 _w(e,t){return{type:`List`,pos:e,nodes:t}}function vw(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function yw(e){return e.type===`EOF`?`end of input`:e.value||e.type}function bw(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 xw(e){return{type:`Variable`,pos:e.pos,idents:Sw(e.value)}}function Sw(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function Cw(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=Tw(i);return{...s,intValue:e}}if(a){let e=Ew(i);return{...s,floatValue:e}}let c=Ew(i);return{...s,complexValue:[0,c]}}function ww(e,t){let n=Ow(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 Tw(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 Ew(e){return Number(e)}function Dw(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+=`
|
|
66
|
+
`;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 VC(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Ow(e,t,n){let r=Dw(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new VC(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function kw(e,t){if(t(e)!==!1)for(let n of Aw(e))kw(n,t)}function Aw(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 QC(e)}}const jw=Symbol(`go-template-js.MISSING`);function Mw(e,t){if(e==null)return jw;if(e instanceof Map)return e.has(t)?e.get(t):jw;if(Array.isArray(e))return jw;if(typeof e==`object`){let n=e;return t in n?n[t]:jw}return jw}function Nw(e,t){let n=e;for(let e of t){if(n===jw)return jw;n=Mw(n,e)}return n}function Pw(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)=>Pw(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)||!Pw(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=>Pw(e[n],t[n])):!1}return!1}const Fw=new WeakSet;function Iw(e){return Fw.add(e),e}function Lw(e){return Fw.has(e)}function Rw(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 zw(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Hw(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Hw(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Uw(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Uw(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Uw(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Uw(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Ww(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Gw(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>qw(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Xw(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Xw(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>aT(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>cT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>cT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>$w(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>nT(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>iT(Xw(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Rw(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Bw(){return{and:Iw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Rw(t))return t;return t}}),or:Iw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Rw(t))return t;return t}})}}function Vw(e,t){return{...zw(e,t),...Bw()}}function Hw(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Pw(e,t)}function Uw(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 Ww(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Gw(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Kw(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 ${Jw(t)}`);return e[t]}throw Error(`index: cannot index ${Jw(e)}`)}function Kw(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 ${Yw(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function qw(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]=Kw(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 Jw(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Yw(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 Xw(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+=Zw(a,t),r=o}return n}function Zw(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Qw={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function $w(e){return e.replace(/[\0"'&<>]/g,e=>Qw[e]??e)}const eT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},tT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function nT(e){let t=``;for(let n of e){let e=eT[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!tT.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const rT=new TextEncoder;function iT(e){let t=``,n=rT.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 aT(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+=oT(l??``,u,d,n,r),o=c+1}return i}function oT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?sT(t,n):sT(t,Zw(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Yw(n)}=${Zw(n,r)})`:sT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return sT(t,cT(n,r,i));case`q`:return sT(t,JSON.stringify(Zw(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Yw(n)}=${Zw(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return sT(t,Number(n).toFixed(i))}case`t`:return sT(t,Rw(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 sT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Yw(n)}=${Zw(n,r)})`:typeof n==`bigint`?sT(t,n.toString(16)):sT(t,Math.trunc(n).toString(16));default:return`%!${e}(${Yw(n)}=${Zw(n,r)})`}}function sT(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 cT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>cT(e,t,n)).join(` `)}]`:e instanceof Map?lT([...e.entries()],t,n):uT(e)?lT(Object.entries(e),t,n):String(e)}function lT(e,t,n){let r=e=>cT(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 uT(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 dT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function fT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function pT(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 mT(e,t,n){e.vars.set(t,n)}const hT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],gT=new Set([`default`,`zero`,`error`]);function _T(e){if(e===void 0)return`default`;if(gT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${vT(e)}`)}function vT(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 yT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${vT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${vT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${vT(e.right)}`);return{left:e.left,right:e.right}}}function bT(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function xT(e){let t=new Set(hT);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 ${hT.join(`, `)}`)}),bT(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 ST=Object.freeze({kind:`break`}),CT=Object.freeze({kind:`continue`}),Xee={kind:`none`};let wT;(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{wT=(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 Zee(e){let t=new Set,n=e=>{kw(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 TT={kind:`dynamic`};function ET(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=PT(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:TT}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return TT;let t=e.cmds[0];if(t===void 0)return TT;let n=t.args[0];return n===void 0||n.type!==`Identifier`?TT:{kind:`call`,name:n.ident,args:t.args.slice(1).map(ET)}}default:return TT}}function Qee(e){let t=[],n=e=>{kw(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(ET);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 $ee=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??kT,this.isT=e.isT??DT,this.missingKey=_T(e.missingKey),this.delims=yT(e.delims),this.funcs=xT({...Vw(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=hw(e,this.delims,t);return wT(n.source,e=>this.evalParsed(n,e),n.defines,Zee(n),Qee(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=dT(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 ST;case`Continue`:throw CT;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 HC(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:QC(e)}}evalIf(e,t,n){Rw(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(Rw(r)){let i=fT(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=lte(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=fT(t,o);if(i.length===1)mT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;mT(a,e,r),mT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===CT)continue;throw e}}}catch(e){if(e===ST)return;throw e}}evalTemplateInvoke(e,t,n){let r=pw(n.defines,e.name);if(!r)throw new HC(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=fT(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=fT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=pw(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 HC(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Xee);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)mT(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 HC(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new HC(`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 UC(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Lw(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){ete(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof GC?new GC(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof JC?new JC(t.message,r,{source:i.source}):t instanceof BC?t:new HC(`error calling ${e}: ${cte(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 PT(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 UC(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 HC(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Nw(e,t);if(i!==jw)return i;if(this.missingKey===`error`)throw new qC(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=pT(t,i);if(!a.found)throw new HC(`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(cT(e,this.toString,this.isT)))}};const DT=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function OT(e){return new $ee(e)}function ete(e,t,n,r,i,a=kT,o=ite,s=DT){let{argTypes:c,arity:l}=t,u=tte(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new WC(e,u,n.length,r,{source:i});let d=nte(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!rte(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new KC(e,t+1,l,r,{source:i}):new GC(e,t+1,jT(c),MT(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(!ote(n[f],l))throw new GC(e,t+1,`${jT(`ordered`)} of the same kind as ${MT(n[f])}`,MT(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!ste(n[p],l))throw new GC(e,t+1,`${jT(`comparable`)} of the same kind as ${MT(n[p])}`,MT(l),r,{source:i})}}}function tte(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 nte(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 rte(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 uT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||uT(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||uT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||uT(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 ate(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function ite(e){return e}function kT(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 GC(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,MT(e),{line:0,column:0,offset:0})}function ate(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function ote(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function ste(e,t){let n=AT(e),r=AT(t);return n===`nil`||r===`nil`?!0:n===r}function AT(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 jT(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 cte(e){return e instanceof Error?e.message:String(e)}function MT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function lte(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?NT([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?NT(Object.entries(e)):[]}function NT(e){return[...e].sort((e,t)=>ute(e[0],t[0]))}function ute(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 PT(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 dte(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function fte(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 FT(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 pte(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=FT(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 mte(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=FT(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 hte(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 gte(e){return JSON.stringify(e)??`null`}function IT(){return{atoi:{fn:e=>dte(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>pte(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>mte(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>fte(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>hte(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>gte(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const LT={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function RT(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*LT[a],n=n.slice(e[0].length)}return t?-r:r}function zT(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<LT.us?`${Math.floor(n)}ns`:n<LT.ms?BT(n,LT.us,3,`µs`):n<LT.s?BT(n,LT.ms,6,`ms`):VT(n),t?`-${r}`:r}function BT(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 VT(e){let t=Math.floor(e/LT.h);e-=t*LT.h;let n=Math.floor(e/LT.m);e-=n*LT.m;let r=Math.floor(e/LT.s),i=e-r*LT.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 HT(e){return e*LT.s}function UT(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 WT(e,t){let n=t().getTime()-UT(e).getTime();return zT(Math.round(n/1e3)*1e9)}const GT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],KT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],qT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],JT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function YT(e){return e<10?`0${e}`:String(e)}function XT(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function ZT(e){return e<10?` ${e}`:String(e)}function QT(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${YT(Math.floor(n/60))}${YT(n%60)}`}function $T(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${YT(Math.floor(n/60))}:${YT(n%60)}`}function eE(e){return`${e>=0?`+`:`-`}${YT(Math.floor(Math.abs(e)/60))}`}function tE(e){return e===0?`Z`:QT(e)}function nE(e){return e===0?`Z`:$T(e)}function rE(e){return e===0?`Z`:eE(e)}function iE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const aE=[[`.000000000`,e=>`.${iE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=iE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${iE(e.ms,6,!1)}`],[`.999999`,e=>{let t=iE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${XT(e.ms)}`],[`.999`,e=>{let t=XT(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>GT[e.month-1]??`January`],[`Monday`,e=>qT[e.weekday]??`Monday`],[`Z07:00`,e=>nE(e.offsetMinutes)],[`-07:00`,e=>$T(e.offsetMinutes)],[`Z0700`,e=>tE(e.offsetMinutes)],[`-0700`,e=>QT(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>KT[e.month-1]??`Jan`],[`Mon`,e=>JT[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>eE(e.offsetMinutes)],[`Z07`,e=>rE(e.offsetMinutes)],[`15`,e=>YT(e.hour)],[`01`,e=>YT(e.month)],[`02`,e=>YT(e.day)],[`_2`,e=>ZT(e.day)],[`03`,e=>YT(e.hour12)],[`04`,e=>YT(e.minute)],[`05`,e=>YT(e.second)],[`06`,e=>YT(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 oE(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of aE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const sE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function cE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const lE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function uE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=cE(new Intl.DateTimeFormat(`en-US`,{...sE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=cE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=dE(cE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=lE.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 dE(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 fE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function pE(e,t){return oE(e,uE(UT(t),fE()))}function mE(e,t,n){return oE(e,uE(UT(t),n))}function hE(e,t){let n=UT(t),r=RT(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function gE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:zT(HT(t))}return typeof e==`bigint`?zT(HT(Number(e))):typeof e==`number`?zT(HT(e)):`0s`}const _E=36e11*24*365,vE=36e11*24*30,yE=36e11*24,bE=36e11,xE=6e10,SE=1e9;function CE(e){let t=RT(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>_E?`${Math.floor(n/_E)}y`:n>vE?`${Math.floor(n/vE)}mo`:n>yE?`${Math.floor(n/yE)}d`:n>bE?`${Math.floor(n/bE)}h`:n>xE?`${Math.floor(n/xE)}m`:n>SE?`${Math.floor(n/SE)}s`:`0s`}function wE(e){let t=uE(UT(e),fE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function TE(e,t){let n=uE(UT(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function EE(e){return e()}const DE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],OE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function kE(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function AE(e,t,n){return[e.slice(t,t+n),t+n]}function jE(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 ME(e,t){for(let[n,r]of DE.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function NE(e,t){for(let[n,r]of OE.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function PE(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 FE(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 IE(e,t){if(e[t]===` `){let[n,r]=jE(e,t+1,1,1);return[n,r]}return jE(e,t,1,2)}function LE(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]=jE(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=jE(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=jE(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function RE(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]=jE(e,t+1,2,2);return[n*r*60,i]}return LE(e,t,n)}function zE(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 BE(e,t,n){let[r,i]=AE(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function VE(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=ME(t,n);return i.month=e,[r,i]}case`Monday`:return[PE(t,n),i];case`Jan`:{let[e,r]=NE(t,n);return i.month=e,[r,i]}case`Mon`:return[FE(t,n),i];case`2006`:{let[e,r]=jE(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=jE(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=jE(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=jE(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=IE(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=jE(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=jE(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=jE(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=jE(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=jE(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=jE(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=jE(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=jE(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=jE(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[zE(t,n),i];case`-0700`:{let[e,r]=LE(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=LE(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]=jE(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=RE(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=RE(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=RE(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]=BE(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]=BE(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]=BE(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 HE=`.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 UE(e,t){let n=0,r=0,i=kE();for(;n<e.length;){let a=!1;for(let o of HE)if(e.startsWith(o,n)){let[e,s]=VE(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 WE(e,t){return UE(e,t)}function GE(e){return String(Math.floor(UT(e).getTime()/1e3))}function KE(e=()=>new Date){return{now:{fn:()=>EE(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>pE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>mE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>hE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>wE(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>TE(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>gE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>CE(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>WE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>WT(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>GE(e),argTypes:[`value`],arity:{kind:`exact`}}}}function qE(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 JE(...e){for(let t of e)if(!qE(t))return t}function YE(e,t){return qE(t)?e:t}function XE(e){return JSON.parse(e)}function ZE(e,t,n){return Rw(n)?e:t}function QE(e){return JSON.stringify(e)??`null`}function $E(e){return JSON.stringify(e,null,2)??`null`}function eD(){return{default:{fn:(e,t)=>YE(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>qE(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>JE(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>ZE(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>XE(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>QE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>$E(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function tD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function nD(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 tD(...t)}function rD(e,t){return e[t]}function iD(e,t){return t in e}function aD(e){return Object.keys(e)}function oD(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 sD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function cD(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 lD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function uD(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function dD(e,t,n){return e[t]=n,e}function fD(e,t){return delete e[t],e}function pD(e){return Object.values(e)}function mD(){return{dict:{fn:(...e)=>tD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>rD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>dD(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>fD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>aD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>pD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>uD(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>lD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>cD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>iD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>oD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>sD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function hD(e){throw new JC(e)}function gD(){return{fail:{fn:e=>hD(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 _D(...e){for(let t of e)if(qE(t))return!1;return!0}function vD(...e){for(let t of e)if(!qE(t))return!0;return!1}function yD(e,t){return[...e,t]}function bD(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 xD(e){return e.filter(e=>!qE(e))}function SD(...e){let t=[];for(let n of e)t.push(...n);return t}const CD={line:0,column:0,offset:0};function wD(e,t,n,r){return new GC(e,t,n,r,CD)}function TD(...e){if(e.length<3)throw wD(`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(!DD(t))throw wD(`dig`,e.length-1,`dict`,OD(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw wD(`dig`,e,`string`,OD(r[e]));return ED(t,n,r,e.length)}function ED(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(!DD(a))throw wD(`dig`,r-1,`dict at intermediate key`,OD(a));return ED(a,t,n.slice(1),r)}function DD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function OD(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function kD(e){return e[0]}function AD(e,t){return t.some(t=>Pw(t,e))}function jD(e){return e.slice(0,-1)}function MD(e){return e[e.length-1]}function ND(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function PD(...e){return e}function FD(e,t){return[t,...e]}function ID(e){return e.slice(1)}function LD(e){return[...e].reverse()}function RD(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function zD(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function BD(e){let t=[];for(let n of e)t.some(e=>Pw(e,n))||t.push(n);return t}function VD(e,...t){return e.filter(e=>!t.some(t=>Pw(t,e)))}function HD(){return{list:{fn:(...e)=>PD(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>kD(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>MD(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>ID(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>jD(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>ND(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>LD(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>BD(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>VD(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>AD(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>xD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>RD(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>SD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>bD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>FD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>yD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>zD(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>yD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>PD(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>TD(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>_D(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>vD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function UD(...e){return e.reduce((e,t)=>e+t,0)}function WD(e){return e+1}function GD(e){return e+1}function KD(...e){return e.reduce((e,t)=>e+t,0)}function qD(e){return Math.ceil(e)}function JD(e,t){return Math.trunc(e/t)}function YD(e,...t){return t.reduce((e,t)=>e/t,e)}function XD(e){return Math.floor(e)}function ZD(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function QD(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function $D(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function eO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function tO(e,t){return e%t}function nO(...e){return e.reduce((e,t)=>e*t,1)}function rO(...e){return e.reduce((e,t)=>e*t,1)}function iO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function aO(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 oO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),aO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return aO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:aO(n,i+t,r).join(` `)}default:return``}}function sO(e,t){return e-t}function cO(e,...t){return t.reduce((e,t)=>e-t,e)}function lO(e){return aO(0,e,e<0?-1:1)}function uO(){return{add:{fn:(...e)=>UD(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>sO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>nO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>JD(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>tO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>$D(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>ZD(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>XD(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>qD(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>iO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>KD(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>cO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>rO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>YD(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>WD(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>GD(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>QD(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>eO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>ZD(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>oO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>lO(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>aO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function dO(e){return Array.from(e)}function fO(e,t){return e===``?dO(t):t.split(e)}function pO(e,t){let n=dO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function mO(e,t,n){let r=dO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const hO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},gO=/^[-_\s]$/,_O=/^\p{P}$/u,vO=/^\p{L}$/u,yO=/^\p{Lu}$/u,bO=/^\p{N}$/u;function xO(e){return e!==void 0&&gO.test(e)}function SO(e){return e!==void 0&&vO.test(e)}function CO(e){return e!==void 0&&yO.test(e)}function wO(e){return e!==void 0&&bO.test(e)}function TO(e){return e!==void 0&&_O.test(e)}function EO(e,t){if(t>=e.length)return{word:{wt:hO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(xO(n)){for(;r<e.length&&xO(e[r]);)r++;return{word:{wt:hO.Connector,text:e.slice(t,r).join(``)},next:r}}if(TO(n)){for(;r<e.length&&TO(e[r]);)r++;return{word:{wt:hO.Punct,text:e.slice(t,r).join(``)},next:r}}if(CO(n)){if(r>=e.length)return{word:{wt:hO.UpperCase,text:n},next:r};if(CO(e[r])){let n=r;for(;n<e.length&&CO(e[n]);)n++;return n<e.length&&SO(e[n])?{word:{wt:hO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:hO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(SO(e[r])){let n=r+1;for(;n<e.length&&SO(e[n])&&!CO(e[n]);)n++;return{word:{wt:hO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:hO.UpperCase,text:n},next:r}}if(SO(n)){for(;r<e.length&&SO(e[r])&&!CO(e[r]);)r++;return{word:{wt:hO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(wO(n)){for(;r<e.length&&wO(e[r]);)r++;return{word:{wt:hO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!xO(e[r])&&!SO(e[r])&&!wO(e[r])&&!TO(e[r]);)r++;return{word:{wt:hO.Other,text:e.slice(t,r).join(``)},next:r}}function DO(e,t,n){if(t.wt!==hO.UpperCase&&t.wt!==hO.Connector){e.push(t.text);return}for(let r of t.text)xO(r)?e.push(n):CO(r)?e.push(r.toLowerCase()):e.push(r)}function OO(e,t){if(e.length===0)return``;let n=dO(e),r=[],{word:i,next:a}=EO(n,0);for(;a<n.length;){i.wt!==hO.Connector&&DO(r,i,t);let e=i,o=i;if({word:i,next:a}=EO(n,a),e.wt===hO.Number){for(;i.wt===hO.Alphabet||i.wt===hO.Number;)DO(r,i,t),{word:i,next:a}=EO(n,a);i.wt!==hO.Invalid&&i.wt!==hO.Punct&&i.wt!==hO.Connector&&r.push(t);continue}if(e.wt===hO.Connector){DO(r,o,t);continue}if(e.wt===hO.Punct)continue;if(i.wt!==hO.Number){i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=EO(n,a),i.wt!==hO.Alphabet){DO(r,s,t),i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t);continue}for(r.push(t),DO(r,s,t);i.wt===hO.Alphabet||i.wt===hO.Number;)DO(r,i,t),{word:i,next:a}=EO(n,a);i.wt!==hO.Invalid&&i.wt!==hO.Connector&&i.wt!==hO.Punct&&r.push(t)}return DO(r,i,t),r.join(``).toLowerCase()}function kO(e){if(e.length===0)return``;let t=dO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!xO(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++,xO(i)&&xO(e)){n.push(e);continue}xO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function AO(e){return kO(e)}function jO(...e){return e.join(` `)}function MO(e,t){return t.includes(e)}function NO(e,t){return t.startsWith(e)}function PO(e,t){return t.endsWith(e)}function FO(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
67
67
|
`).map(e=>n+e).join(`
|
|
68
68
|
`)}function IO(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 LO(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw wD(`join`,2,`list of strings/primitives`,`list element of type ${RO(e)}`);n.push(String(e))}return n.join(e)}function RO(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function zO(e){return OO(e,`-`)}function BO(e){return e.toLowerCase()}function VO(e,t){return`\n${FO(e,t)}`}function HO(e){return e.replace(/\s+/g,``)}function UO(e,t,n){return n===1?e:t}function WO(...e){return e.map(e=>`"${e}"`).join(` `)}function GO(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function KO(e,t){return t.repeat(Math.max(0,e))}function qO(e,t,n){return fO(e,n).join(t)}function JO(e){return OO(e,`_`)}function YO(e,t){let n=fO(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function XO(e,t){return fO(e,t)}function ZO(e,t,n){let r=QO(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function QO(e,t,n){if(n===0)return[];let r=fO(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 $O(...e){return e.map(e=>`'${e}'`).join(` `)}function ek(e,t,n){let r=dO(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 tk(e){let t=``;for(let n of e)nk(n)?t+=n.toLowerCase():rk(n)?t+=n.toUpperCase():t+=n;return t}function nk(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function rk(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function ik(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function ak(e){return e.trim()}function ok(e,t){if(e.length===0)return t;let n=new Set(dO(e)),r=dO(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 sk(e,t){return t.startsWith(e)?t.slice(e.length):t}function ck(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function lk(e,t){let n=dO(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 uk(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function dk(e){return e.toUpperCase()}function fk(e,t){return pk(e,`
|
|
69
69
|
`,t)}function pk(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
70
|
-
`)){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 mk(e,t,n){return pk(e,t,n)}function hk(){return{abbrev:{fn:(e,t)=>pO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>mO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>AO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>jO(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>MO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>NO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>PO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>FO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>IO(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>LO(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>zO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>BO(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>VO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>UO(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>WO(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>GO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>KO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>qO(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>JO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>YO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>XO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>ZO(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>$O(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>ek(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>tk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>ik(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>ak(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>ok(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>sk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>ck(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>lk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>uk(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>dk(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>fk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>mk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}const gk=OT({fromString:e=>e}),_k=[`plugins`,`repo`];function vk({scope:e,name:t}){return`${e}.${t}`}function yk(e){return t=>t===e||t.startsWith(`${e}.`)}const bk=`self`;function xk(e){return _k.find(t=>e===t||e.startsWith(`${t}.`))}function Sk(e,t){let n=xk(e);if(n===void 0||n===e)return``;let r=_k.filter(e=>e!==n).map(t=>`${t}${e.slice(n.length)}`).find(t);return r===void 0?``:` ("${r}" is declared: a repository's own plugins are named under repo., installed ones under plugins., and a name in one is never looked up in the other)`}function Ck(e,t){let n=Cx[e],r=kx(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 wk=Object.fromEntries([...Lx].map(([e,t])=>[t,Ck(e,t)])),Tk={subscribers:`number`,fps:`number`,shown:`boolean`},Ek=Object.keys(Tk),Dk={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},"session.id":{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:``},...wk,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Wb.flatMap(e=>Ek.map(t=>[Yb(e,t),{kind:`input`,path:Yb(e,t),type:Tk[t],default:Jb[t]}]))),[qb(`by`)]:{kind:`input`,path:qb(`by`),default:Kb.by},[qb(`fps`)]:{kind:`input`,path:qb(`fps`),type:`number`,default:0},...Object.fromEntries([`label`,`fg`,`bg`,`open`].map(e=>[`diagnostics.${e}`,{kind:`input`,path:`diagnostics.${e}`,default:``}])),"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:``},"location.main":{kind:`input`,path:`location.main`,default:``},"location.worktree":{kind:`input`,path:`location.worktree`,default:``},"location.subpath":{kind:`input`,path:`location.subpath`,default:``},"location.noRepo":{kind:`input`,path:`location.noRepo`,type:`boolean`,default:!1},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Ok={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`,diagnostics:`the errors and warnings the draw owes its reader`};function kk(e){let t=e.split(`.`,1)[0];return Object.hasOwn(Ok,t)?t:void 0}const Ak=Object.fromEntries(sy.map(e=>[e,Lx.get(e)]));function jk(e){return sy.find(t=>Ak[t]===e)}function Mk(e){let t=OS(e);return Fi.find(e=>t.startsWith(OS(e)))}function Nk(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:q(e.source,[`root`])})}function Pk(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=xk(i);t!==void 0&&(r!==`variables`&&i===t||r===`segments`&&n.has(i)||e.issues.push({path:`${r}.${i}`,message:`"${i}" is in "${t}", the namespace plugins own (each declares its names there from its own definition) — rename it`,line:q(e.source,[r,i])}))}for(let[r,i]of Object.entries(t.segments??{}))for(let t of Object.keys(i.vars??{})){let i=`${r}.${t}`,a=()=>({path:`segments.${r}.vars.${t}`,line:q(e.source,[`segments`,r,`vars`,t])});if(Lk(i)){e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", ${Fk} — rename the var or the segment`});continue}let o=xk(i);o===void 0||n.has(r)||e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", in "${o}", the namespace plugins own — rename the var or the segment`})}}const Fk=`supplied by the daemon's payload to every config`;function Ik(e,t,n){let r=mb(t);return n.filter(Lk).map(t=>{let n=r([`variables`,t]);return`${n===void 0?e:`${e}:${n}`}: "${t}" is ${Fk}, so this declaration is ignored — remove it`})}function Lk(e){return Object.hasOwn(Dk,e)}const Rk=`edit.mode`,zk=`edit.configure`,Bk=`edit.toggle`,Vk=`arrange`,Hk=`${Pi}draft.`;function Uk(e,t){return`${e}:${t}`}const Wk={variable:Rk,key:Rk,member:Vk},Gk=Ci(Wk);function Kk(e){try{return gk.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function qk(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??{})){let e=[t.template,t.bg,t.fg,...Object.values(t.partials??{})];for(let t of e)if(typeof t==`string`&&Kk(t))return!0}return!1}function Jk(e,t){if(Nk(e,t,Pi,`edit mode`),!qk(t))return;let{variables:n,actions:r}=Yk();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Yk(){return{variables:{[Rk]:{...Oi(Rk,gi),within:[zi]},[zk]:{...Oi(zk,gi),within:[Wk]}},actions:{[Bk]:ki(Rk,Vk),"edit.unconfigure":{set:zk,to:gi}}}}function Xk(e,t,n,r){let i={variable:e,key:e,member:_i};return r.variables[e]={...Oi(e,gi),...n.length>0&&{within:n}},r.actions[e]=ki(e,_i),r.segments[e]={template:Ti(e,`(?)`,`✕`),...Zk(n)},Si(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 Zk(e){let[t,...n]=e;return t===void 0?{}:{when:Ci(t,...n)}}const Qk=`none`;function $k(e){return Fu(e,`background`)}var eA=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=nA(n,i),l=c!==Qk,u=l?c===void 0?o:rA(a,c,`bg`):$k(a);e.bg=u;let d=nA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:kv(a,e,t))(u):void 0:rA(a,d,`fg`);return new U({...l&&{bgcolor:H.fromRgba(u)},...f!==void 0&&{color:H.fromRgba(f)}})}function nA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function rA(e,t,n){try{return Fu(e,t)}catch(e){throw e instanceof Pu?new eA(t,n,e.message):e}}const iA=`🔧`,aA={help:[`-h`,`--help`],version:[`-V`,`--version`]},oA=[...new Set(Object.values(Ub).map(e=>$S(e.switch.setting)))].join(` or `),sA=Math.max(...Object.values(Mx).map(e=>e.configKey.length))+2,cA=[`✚ inserts`,`✖ removes`,`${iA} configures`,`↺ resets layout`],lA={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:[`draws the bar in the tmux status line, while this session's pane is the one it shows`,`tmux: the daemon draws it there · claude: puts the status line back as it was`]},uA=`
|
|
70
|
+
`)){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 mk(e,t,n){return pk(e,t,n)}function hk(){return{abbrev:{fn:(e,t)=>pO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>mO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>AO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>jO(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>MO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>NO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>PO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>FO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>IO(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>LO(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>zO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>BO(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>VO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>UO(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>WO(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>GO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>KO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>qO(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>JO(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>YO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>XO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>ZO(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>$O(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>ek(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>tk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>ik(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>ak(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>ok(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>sk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>ck(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>lk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>uk(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>dk(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>fk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>mk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}const gk=OT({fromString:e=>e}),_k=[`plugins`,`repo`];function vk({scope:e,name:t}){return`${e}.${t}`}function yk(e){return t=>t===e||t.startsWith(`${e}.`)}const bk=`self`;function xk(e){return _k.find(t=>e===t||e.startsWith(`${t}.`))}function Sk(e,t){let n=xk(e);if(n===void 0||n===e)return``;let r=_k.filter(e=>e!==n).map(t=>`${t}${e.slice(n.length)}`).find(t);return r===void 0?``:` ("${r}" is declared: a repository's own plugins are named under repo., installed ones under plugins., and a name in one is never looked up in the other)`}function Ck(e,t){let n=Sx[e],r=Ox(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 wk=Object.fromEntries([...Ix].map(([e,t])=>[t,Ck(e,t)])),Tk={subscribers:`number`,fps:`number`,shown:`boolean`},Ek=Object.keys(Tk),Dk={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},"session.id":{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:``},...wk,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Ub.flatMap(e=>Ek.map(t=>[Jb(e,t),{kind:`input`,path:Jb(e,t),type:Tk[t],default:qb[t]}]))),[Kb(`by`)]:{kind:`input`,path:Kb(`by`),default:Gb.by},[Kb(`fps`)]:{kind:`input`,path:Kb(`fps`),type:`number`,default:0},...Object.fromEntries([`label`,`fg`,`bg`,`open`].map(e=>[`diagnostics.${e}`,{kind:`input`,path:`diagnostics.${e}`,default:``}])),"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:``},"location.main":{kind:`input`,path:`location.main`,default:``},"location.worktree":{kind:`input`,path:`location.worktree`,default:``},"location.subpath":{kind:`input`,path:`location.subpath`,default:``},"location.noRepo":{kind:`input`,path:`location.noRepo`,type:`boolean`,default:!1},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Ok={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`,diagnostics:`the errors and warnings the draw owes its reader`};function kk(e){let t=e.split(`.`,1)[0];return Object.hasOwn(Ok,t)?t:void 0}const Ak=Object.fromEntries(oy.map(e=>[e,Ix.get(e)]));function jk(e){return oy.find(t=>Ak[t]===e)}function Mk(e){let t=DS(e);return Fi.find(e=>t.startsWith(DS(e)))}function Nk(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:q(e.source,[`root`])})}function Pk(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=xk(i);t!==void 0&&(r!==`variables`&&i===t||r===`segments`&&n.has(i)||e.issues.push({path:`${r}.${i}`,message:`"${i}" is in "${t}", the namespace plugins own (each declares its names there from its own definition) — rename it`,line:q(e.source,[r,i])}))}for(let[r,i]of Object.entries(t.segments??{}))for(let t of Object.keys(i.vars??{})){let i=`${r}.${t}`,a=()=>({path:`segments.${r}.vars.${t}`,line:q(e.source,[`segments`,r,`vars`,t])});if(Lk(i)){e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", ${Fk} — rename the var or the segment`});continue}let o=xk(i);o===void 0||n.has(r)||e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", in "${o}", the namespace plugins own — rename the var or the segment`})}}const Fk=`supplied by the daemon's payload to every config`;function Ik(e,t,n){let r=pb(t);return n.filter(Lk).map(t=>{let n=r([`variables`,t]);return`${n===void 0?e:`${e}:${n}`}: "${t}" is ${Fk}, so this declaration is ignored — remove it`})}function Lk(e){return Object.hasOwn(Dk,e)}const Rk=`edit.mode`,zk=`edit.configure`,Bk=`edit.toggle`,Vk=`arrange`,Hk=`${Pi}draft.`;function Uk(e,t){return`${e}:${t}`}const Wk={variable:Rk,key:Rk,member:Vk},Gk=Ci(Wk);function Kk(e){try{return gk.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function qk(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??{})){let e=[t.template,t.bg,t.fg,...Object.values(t.partials??{})];for(let t of e)if(typeof t==`string`&&Kk(t))return!0}return!1}function Jk(e,t){if(Nk(e,t,Pi,`edit mode`),!qk(t))return;let{variables:n,actions:r}=Yk();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Yk(){return{variables:{[Rk]:{...Oi(Rk,gi),within:[zi]},[zk]:{...Oi(zk,gi),within:[Wk]}},actions:{[Bk]:ki(Rk,Vk),"edit.unconfigure":{set:zk,to:gi}}}}function Xk(e,t,n,r){let i={variable:e,key:e,member:_i};return r.variables[e]={...Oi(e,gi),...n.length>0&&{within:n}},r.actions[e]=ki(e,_i),r.segments[e]={template:Ti(e,`(?)`,`✕`),...Zk(n)},Si(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 Zk(e){let[t,...n]=e;return t===void 0?{}:{when:Ci(t,...n)}}const Qk=`none`;function $k(e){return Fu(e,`background`)}var eA=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=nA(n,i),l=c!==Qk,u=l?c===void 0?o:rA(a,c,`bg`):$k(a);e.bg=u;let d=nA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:kv(a,e,t))(u):void 0:rA(a,d,`fg`);return new U({...l&&{bgcolor:H.fromRgba(u)},...f!==void 0&&{color:H.fromRgba(f)}})}function nA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function rA(e,t,n){try{return Fu(e,t)}catch(e){throw e instanceof Pu?new eA(t,n,e.message):e}}const iA=`🔧`,aA={help:[`-h`,`--help`],version:[`-V`,`--version`]},oA=[...new Set(Object.values(Hb).map(e=>QS(e.switch.setting)))].join(` or `),sA=Math.max(...Object.values(jx).map(e=>e.configKey.length))+2,cA=[`✚ inserts`,`✖ removes`,`${iA} configures`,`↺ resets layout`],lA={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:[`draws the bar in the tmux status line, while this session's pane is the one it shows`,`tmux: the daemon draws it there · claude: puts the status line back as it was`]},uA=`
|
|
71
71
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
72
72
|
|
|
73
73
|
Usage: cc-candybar [options]
|
|
@@ -91,12 +91,12 @@ Configuration:
|
|
|
91
91
|
the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
|
|
92
92
|
and 💾 save, which appears while you have unsaved changes and writes them to
|
|
93
93
|
your config file. Under it are its
|
|
94
|
-
tabs, ${
|
|
95
|
-
${
|
|
94
|
+
tabs, ${WS.map(e=>e.label).join(`, `)};
|
|
95
|
+
${GS.session} holds quick actions and commands, ${GS.layout} a new preset.
|
|
96
96
|
A change applies to this session at once.
|
|
97
97
|
Where each setting is in the menu: the globals field that sets it in a
|
|
98
98
|
config file, then the control's label.
|
|
99
|
-
${
|
|
99
|
+
${$S().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${jx[e].configKey.padEnd(sA)}${jx[e].label}`)]).join(`
|
|
100
100
|
`)}
|
|
101
101
|
The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
|
|
102
102
|
failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
|
|
@@ -105,7 +105,7 @@ ${eC().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${Mx[e].config
|
|
|
105
105
|
in place. In edit mode: ${cA.join(`, `)}.
|
|
106
106
|
|
|
107
107
|
Animation lanes (each switched in the settings menu's ${oA}):
|
|
108
|
-
${
|
|
108
|
+
${Ub.map(e=>` ${Hb[e].label}\n${lA[e].map(e=>` ${e}`).join(`
|
|
109
109
|
`)}`).join(`
|
|
110
110
|
`)}
|
|
111
111
|
|
|
@@ -137,7 +137,7 @@ Subcommands:
|
|
|
137
137
|
Claude Code's statusline JSON from stdin (one object
|
|
138
138
|
a line) and sends it as the session's data
|
|
139
139
|
(--config rides with it). LANE is one of
|
|
140
|
-
${
|
|
140
|
+
${Ub.join(`, `)}:
|
|
141
141
|
the experimental lane this stream serves,
|
|
142
142
|
which streams only while its toggle in the settings
|
|
143
143
|
menu's ${oA} is on.
|
|
@@ -146,8 +146,8 @@ Subcommands:
|
|
|
146
146
|
pushes it, while this pane is shown. The bar is
|
|
147
147
|
drawn at PANE's width, so split PANE with -v for a
|
|
148
148
|
pane under it that fits. Experimental:
|
|
149
|
-
runs while ${
|
|
150
|
-
menu's ${
|
|
149
|
+
runs while ${Hb.pane.label} is on in the settings
|
|
150
|
+
menu's ${QS(Hb.pane.switch.setting)}.
|
|
151
151
|
|
|
152
152
|
Config tooling:
|
|
153
153
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -173,23 +173,23 @@ Config tooling:
|
|
|
173
173
|
config [--json] The effective merged config. (All three query the
|
|
174
174
|
running daemon; none spawn one.)
|
|
175
175
|
|
|
176
|
-
`,dA=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function fA(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function pA(e,t,n){return E.resolve(e,fA(t,n))}function mA(e,t,n){return typeof t==`string`&&t!==``?pA(e,t,n):void 0}const hA=`CC_CANDYBAR_CONFIG`;function gA({env:e,home:t},n){return mA(n,e[hA],t)}function _A(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function vA(e,t,n){return _A(mA(n,e,t.home),gA(t,n))}function yA(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const bA=new Nf({"strip.separator":`default`,"strip.rail":`default`});function xA(e){return bA.resolve(e)}const SA={kind:`still`},CA=e=>Mp.at(e.timeline,e.wall),wA=Symbol(`bar`);function TA(e){return e.name!==
|
|
176
|
+
`,dA=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function fA(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function pA(e,t,n){return E.resolve(e,fA(t,n))}function mA(e,t,n){return typeof t==`string`&&t!==``?pA(e,t,n):void 0}const hA=`CC_CANDYBAR_CONFIG`;function gA({env:e,home:t},n){return mA(n,e[hA],t)}function _A(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function vA(e,t,n){return _A(mA(n,e,t.home),gA(t,n))}function yA(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const bA=new Nf({"strip.separator":`default`,"strip.rail":`default`});function xA(e){return bA.resolve(e)}const SA={kind:`still`},CA=e=>Mp.at(e.timeline,e.wall),wA=Symbol(`bar`);function TA(e){return e.name!==py}function EA(e){return t=>G.map(G.all(e.map(({timeline:e,effect:n})=>Mp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const DA=Nd;function OA(e,t){let n=new nu(t,DA.foregroundColor,DA.ansiColors,DA.palette);return t=>e({...t,theme:n})}function kA(e,t){return n=>Oh(()=>e(n),...t)(n)}function AA(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 jA=4096;function MA(e,t,n){let r=(n,{terminal:r})=>({...n,bg:r.bg?n.bg:e,fg:r.fg?n.fg:r.bg?e:t}),i=e=>e,a=Qb.reduceRight((e,{lit:t,seconds:n})=>G.sequence(G.constant(t?r:i),n,e),G.constant(i)),o=G.sequence(G.constant(i),n,a);return()=>o}var NA=class{inForce=null;anchor=Mp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:py,t:0,speed:1,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.passages?.size??0;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}clockAt(e,t){return{wall:e,timeline:Mp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=CA(t),a=e=>Mp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:wA,name:e,t:i-o.since},c=this.placements,l=new Map,u=this.made,d=new Map,f=[],{last:p}=n,m=this.passages,h=n.transitions?m!==null&&p!==null?`compared`:`fresh`:`off`,g=h===`compared`?e=>{let t=p.placements.get(e);return t?.kind===`drew`?{drawing:t.drawing,passage:m.get(e)??null}:void 0}:null,_=new Set,v=new Map,y=[],b=[],x={effect:e,t:s.t,speed:t.timeline.rate,made:0,reused:0,own:f,basis:h,revision:n.source.revision,fades:y,leaves:b},S=(e,t,{ground:n})=>{let r=qg.transitions[e]({z:AA(`${this.key}@${t}`)*jA});return{name:e,since:i,done:e=>r.done(e),effect:OA(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},ee=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},te=(e,t)=>{let n=l.get(e)??c.get(e),r=n?.name===t?n:{name:t,since:i},a=i-r.since;return l.has(e)||(l.set(e,r),f.push({placement:e,effect:t,t:a})),{scope:e,name:t,t:a}},E=(e,t)=>{let n=d.get(e)??new Map;d.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=u.get(e)?.get(t.scope),a=i?.name===t.name,o=AA(t.scope===wA?e:`${e}@${t.scope}`),s=a?i.effect:qg.loops[t.name]({z:o*jA});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},ne=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:te(r.id,r.effect),i=t.get(e.scope);i===void 0?t.set(e.scope,{...e,owners:[n]}):i.owners.push(n)}return[...t.values()]},D=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=t.get(r.id);e===void 0?t.set(r.id,[n]):e.push(n)}return[...t].flatMap(([e,t])=>{let n=v.get(e)??null;return n===null?[]:[{timeline:a(i-n.since),effect:Oh(n.effect,...t)}]})},re=r===null?[]:[{timeline:Mp.play(r.idleSince),effect:MA(r.fill,r.text,nx(r.timeoutS))}],ie=e=>e===`menu`?re:[];return{placed:h===`off`?(e,t)=>t:ee,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?ne(r):[{...s,owners:void 0}]).filter(TA),o=D(r),c=ie(n);if(i.length===0&&o.length===0&&c.length===0)return SA;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new vh(e,EA([...i.map(e=>{let t=E(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:kA(t,e.owners)}}),...o,...c]),{key:l,theme:DA})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},PA=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new NA(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}}};const FA={fg:`#ffffff`,bg:`#c82828`},IA={fg:`#000000`,bg:`#dca028`},LA={fg:`#ffffff`,bg:`#2f6db5`};function RA(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const zA=RA(38,FA.fg),BA=RA(48,FA.bg),VA=[[0,31],[127,159],[8234,8238],[8294,8303]];function HA(e){return VA.some(([t,n])=>e>=t&&e<=n)}function UA(e){let t=``;for(let n of e)t+=HA(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function WA(e,t){let n=UA(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const GA=`${BA}${zA}`;function KA(e){return`⚠ cc-candybar: ${JA(e)}`}function qA(e){return`${GA}${KA(e)}[0m\n`}function JA(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: ${WA(e.message,60)}`;case`render_failed`:return`render failed: ${WA(e.message,60)}`;case`switched_off`:return`switched off: ${WA(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${WA(e.message,60)}`}}function YA(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function XA(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:UA(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function ZA(e){return XA(KA({kind:`permanent`,cause:`render_failed`,message:e}),FA)}function QA(e,t){try{return e(t)}catch(t){return e(XA(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,FA))}}function $A(e){return e.type===V.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const ej=Object.keys(new U().attributes);function tj(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=ej.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:$A(n)},...r!==void 0&&{bg:$A(r)},...i.length>0&&{attrs:i}}}function nj({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&tj(t,n),...t?.link!==void 0&&{link:t.link}}}function rj(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return W.splitLines(n).map(e=>e.map(e=>nj(e,t)))}function ij({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new W(e,new U({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function aj(e,t){let n=Nl(t);return e.map(e=>mh(e.map(ij),n)).join(`
|
|
177
177
|
`)}function oj(e){return aj(e.rows.map(e=>e.runs),e.depth)}function sj(e){return oj(e)+`
|
|
178
178
|
`}const cj=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function lj({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&cj(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function uj(e){return e.map(e=>e.text).join(``)}const dj={};function fj(e,t){let n=Nl(t.colorSystem),{time:r}=t,i=1/0,a=[...ip(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:bA,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:dj}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:rj(a,n.colorSystem),nextChange:Math.min(W.nextChange(a),i)}}const pj=new Map;function mj(e){let t=pj.get(e);if(t!==void 0)return t;let n=t=>({seam:t.seam.map(t=>`cap`in t?t:{...t,glyph:e})}),{seam:r,caps:i}=dh.plain,a=new Fm({glyph:n(r.glyph),ascii:r.ascii},i);return pj.set(e,a),a}function hj(e,t){return e===`plain`&&t!==void 0?mj(t):dh[e]}const gj=new Map;function _j(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=gj.get(t);if(n!==void 0)return n;let r=hj(e.endcaps,e.separator),i=e=>new K(`x`,{end:``,overflow:`ignore`,style:new U({bgcolor:e})}),a=e=>{let{lines:t}=fj(new lm(e,r),{colorSystem:null});return new K(uj(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return gj.set(t,s),s}function vj(e){return _j(e).chrome}function yj(e){return _j(e).seam}const bj=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function xj(e){return[...new Set(e.match(bj)??[])].join(``)}function Sj(e){let t=hj(e.endcaps,e.separator),n=e=>new K(`x`,{end:``,style:new U({bgcolor:e})}),{lines:r}=fj(new lm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return xj(uj(r.flat()))}function Cj(e){return e.wrap?e.width:1/0}function wj(e,t){return fj(new K(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(uj)}function Tj(e,t,n=SA){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=hj(t.endcaps,t.separator),i=Number.isFinite(Cj(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new E_([...e],{joiner:r}):new lm([...e],r),s=n.kind===`still`?fj(o,a):fj(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function Ej(e,t){return aj(Tj(e,t).lines,t.colorCompatibility)}const Dj=[`moves`,`can-move`,`still`];function Oj(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const kj=[`statusline`,`frames`],Aj=e=>e?.kind===`frames`?`frames`:`statusline`,jj=[`carried`,`missing`,`unanswered`];function Mj(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:Oj(e)===`no`?`unanswered`:`missing`}function Nj(e){return{path:e.transcript_path,answered:Oj(e)===`yes`}}const Pj=[...Dj,`failed`,`drawing`];var Fj=class{seen=new Map;see(e,t,n,r){let i=Aj(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 Ij={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`}}},Lj=e=>Ij[e];function Rj(e){return Lj(e).glyphs.kind===`bundled`}function zj(e){return Lj(e).glyphs.kind===`configured`}const Bj=e=>Lj(e).label,Vj=[{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 Hj(e,t){let n=t.codePointAt(0);return Vj.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&Gj(e,t)===!0)}const Uj=Object.keys(Ij);function Wj(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function Gj(e,t){let n=Wj(e),r=Wj(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 Kj(e){for(let t of Uj){let n=Lj(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 qj(e){let t=Uj.find(t=>Lj(t).term===e);return t===void 0?null:{name:t,version:null}}function Jj(e){let t=Kj(e.termtype)??qj(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 Yj(e){let t=e.TERM_PROGRAM,n=Uj.find(e=>Lj(e).program===t),r=n===void 0?qj(e.TERM):{name:n,version:Lj(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 Xj(e){switch(e.kind){case`known`:return Bj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function Zj(e){switch(e.kind){case`known`:return Bj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Qj({name:e,version:t}){let n=Lj(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=Gj(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const $j=Uj.filter(e=>Lj(e).links!==null).map(Bj).join(`, `);function eM(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(!is(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||!is(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function tM(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 nM=[`managed`,`project`],rM=e=>!nM.includes(e.scope),iM={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:rs(t.projectDir)}),user:e=>({scope:`user`,path:e})},aM=[`drawn`,`boxes`],oM=1024*1024,sM=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function cM(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 lM(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const uM=wc.truecolor;function dM(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 fM={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>dM(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=tM(t.sources,uM);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:`${uM} 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`,uM],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=iM[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 ${uM} to "1" there`}:o(s)})},pM={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>dM(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"})},mM={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:`${sM(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's diagnostics name), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${sM(e.value.of)} measured`}},hM={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},gM={argument:`command argument`,environment:`$${hA}`,pick:`load-config pick`,unknown:`source unknown`};function _M({target:e,layers:t}){return e.source===`search`?t.length===0?yA(t):`${yA(t)} (searched)`:`${e.path} (${gM[e.source]})`}function vM(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
179
|
-
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${hM[e]}`)]}}const yM={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=_M(e),n=lM(vM(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},bM="re-run `cc-candybar install`";function xM(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:// — ${bM}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${bM}`]}const SM={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.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${bM}`};case`lost`:return lM([...xM(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 CM({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 wM(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Wb.join(`|`)}>\``:e.checkout===null?bM:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function TM(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 — ${wM(e,`native`)}`];let{bundle:i,source:a}=CM(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} — ${wM(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 — ${wM(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 EM=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)`},DM={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`:`${EM(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:lM([...new Set(i.flatMap(e=>TM(n,r,e)))])}};function OM({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||Rr(e.identity,t.value.through)):[]}function kM(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const AM={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`?kM(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return lM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=OM(e.value,n),u=lM([...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 ${Fr(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 ${Fr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Vr(o.charge.bytes,s)?[`the daemon holds ${Gr(o.charge)} of its ${Fr(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}}}},jM=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function MM(e,t){let n=Xj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Qj(e.terminal):{kind:`unknown`}}function NM({identified:e,tmuxClient:t},n){let r=Zj(e),i=MM(e,n),a=Xj(e)===null?jM:`${jM}, 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: ${$j}`];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 PM={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 lM(NM(t,n))}}},FM=e=>e.filter(e=>e.role===`statusline`),IM={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})=>zM(e,LM(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`:EM(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}}},LM=e=>{let t=FM(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, a placement with an effect of its own that is not drawn now, or a moving bar handed off to another lane, which comes back here when the handoff ends)`}: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 zM(e,t){let n=eM(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 rM(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 BM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function VM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return Zj(e);case`bundling`:case`unread`:case`configured`:return[Bj(e.name),e.version].filter(e=>e!==null).join(` `)}}function HM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return Xj(e);case`bundling`:case`unread`:return Bj(e.name);case`configured`:{let t=Bj(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 UM(e){let t=HM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${BM(e.glyphs)}`}}const WM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=UM(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=VM(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 ${BM(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:Gj(i.version,e);if(t===!0)return{ok:!0};let n=Bj(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 ${BM(n)} — set a Nerd Font as its font`)}}}};function GM(e){return e.join(`, `)}function KM(e){return`or set missingData: "ignore" on ${GM(e)}`}function qM(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, ${KM(t)}`]:[`${GM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${KM(t)}`]}function JM(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)}: ${EM(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)}`]:[]}const YM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>lM([...qM(e.pullRequests),...JM(e.rateLimits,t)])};function XM({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 ${oM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const ZM=[yM,DM,AM,SM,PM,fM,pM,mM,IM,WM,YM,{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`:`${EM(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:lM(e.value.flatMap(XM))}],QM=ZM.filter(e=>e.takesMark);function $M(e){return ZM.map(t=>({check:t,verdict:t.probe(e)}))}function eN(e){return ZM.find(t=>t.name===e)}const tN=`${P}doctor.`;function nN(e){let t=`${tN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function rN({target:e}){return`configTarget=${e.source}`}function iN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?Xj(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 aN(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 oN(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}=CM(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const sN=e=>`${e>=0?`+`:``}${Fr(e)}`;function cN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${kM(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`:`${OM(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Kr(i.charge)}${i.charge.kind===`stand-in`?`(${sN(-i.charge.gap)})`:``}:${Fr(i.charge.bytes)}`}/${Fr(a)} postMortems=${s}`}function lN(e){return`data=pr:${(()=>{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`})()},rateLimits:${(()=>{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`)}`})()}`}function uN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>dN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${R(i)}`;let a=FM(r.flatMap(e=>e.bars));return`frames=${Pj.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${R(i)}`}function dN(e){let t=eM(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 fN(e){let t=tM(e,uM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${R(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function pN(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 mN(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=UM(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 hN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function gN(e){return e.flatMap(({check:e,verdict:t})=>{let n=nN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Ny},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:hN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Ny:My},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const _N={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function vN(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(_N).map(([t,n])=>[`${e}${t}`,n]))}}const yN=`armed`,bN=`disarmed`,xN=`.armed`,SN=e=>e.endsWith(xN);function CN(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function wN(e,t,n){let r=`${e}${xN}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${yN}")`,s=CN(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:yN},[a]:{set:r,to:bN},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:bN}},disarm:a}}const TN=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function EN(e){return typeof e==`string`&&TN.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 DN(e){let t=EN(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const ON=[`/compact`,`/model`],kN=`/clear`;function AN(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=wN(`${e}clear`,{arm:kN,confirm:`${kN} ✓ confirm`},[{action:n,when:`true`}]);return{template:ON.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Hb} }}`,actions:{...Object.fromEntries(ON.map(e=>[t(e),{slash:DN(e)}])),...r.actions,[n]:{slash:DN(kN)}},variables:r.variables,disarm:r.disarm}}const jN=Array.from({length:10},(e,t)=>(t+1)*1e5),MN=jN[0],NN=jN[jN.length-1];function PN(e){let t=ts(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=MN&&n<=NN?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${MN}–${NN} tokens)`,`parse`)}function FN(e,t){let n=Math.min(t??NN,NN),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:jN.filter(e=>e<r).at(-1)??0,higher:jN.find(e=>e>r&&e<=n)??0}}function IN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Hb} }}{{ 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:DN(`/autocompact auto`)},...Object.fromEntries(jN.map(t=>[`${e}${t}`,{slash:DN(`/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 }}`,RN=`${P}edit`,zN=`${P}toolbar`,BN=vN(P),VN=`${P}commands`,HN=AN(`${VN}.`),UN=`${P}autocompact`,WN=IN(`${UN}.`,LN),GN=e=>({kind:`segment`,name:e}),KN=`${P}tab`,qN=e=>`${KN}.${e}`,JN=e=>`${qN(e)}.toggle`,YN=e=>({variable:KN,key:KN,member:e}),XN=`${P}save`,ZN=`${P}preset.save`,QN=`${P}preset.delete`,$N=e=>`${P}${e}`,eP=e=>`${P}apply.${e}`,tP=e=>`${P}reset.${e}`,nP=`${P}themeDefault.save`,rP=`${P}themeDefault.differs`,iP=`${P}themeDefault.theme`,aP={when:`{{ .${rP} }}`,template:`{{ action "${nP}" (printf "⤓ default for %s" .${iP}) }} {{ swatch "${eP(`theme`)}" .${iP} }}`},oP=`${P}resetAll`,sP=`${Li}.toggle`,cP=`${P}undo`,lP=`${P}back`,uP=`${lP}.step`,dP=`${P}navigation.back`,fP=lP,pP={template:`{{ if gt .${dP} 0 }}{{ action "${lP}" "◁" }}{{ else }}{{ fg (${dA}) "◁" }}{{ end }}`},mP=`${P}redo`,hP=`${P}doctor`,gP=`${hP}.run`,_P=e=>`${hP}.fix.${e}`,vP=(e,t)=>`${hP}.mark.${e}.${t}`,yP=e=>`${hP}.${e}`,bP={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},xP=jS(`${P}pickers`),SP=e=>`${P}${e}`,CP=e=>`${SP(e)}.toggle`,wP=e=>XS(e)?jS(`${P}${e}Pickers`):xP,TP=e=>{let t=wP(YS[qS[e].beside]);return{variable:t,key:t,member:e}},EP={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${QN}" (printf "🚮 delete %s" .${Mx.preset.effectiveVar}) }}`}},DP=(e,t)=>`${P}list.${e}.${t}`,OP=e=>`${P}resettable.${e}`,kP=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${OP(e.name)})`).join(` `)})`,AP=Wb.map(e=>[Ub[e].switch.setting,e]),jP={variables:{},actions:{},segments:{}},MP=Object.fromEntries(AP.map(([e,t])=>[e,Xk(`${P}help.${e}`,lA[t],[],jP)])),NP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],PP=e=>{let t=t=>`.${Yb(e,t)}`,n=NP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Mx[Ub[e].switch.setting].effectiveVar} ${JSON.stringify(Ub[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},FP=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${Bi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,IP=`${P}fps`,LP=`{{ if eq .${qb(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${qb(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,RP=Object.fromEntries(AP.map(([e,t])=>[e,PP(t)])),_te=e=>JS.filter(t=>qS[t].beside===e),zP=Object.keys(Mx).map(e=>{let t=Mx[e],n=YS[e];return{...t,name:e,place:n,control:US({label:t.label,domain:rC(t.configKey)},t.sessionKey,t.effectiveVar,eP(e),wP(n)),beneath:t.previews.map(e=>EP[e]),help:[MP[e]].filter(e=>e!==void 0),submenus:_te(e)}}),vte=e=>zP.filter(t=>t.place===e),yte=e=>zP.filter(t=>ZS(t.place,e)),BP=e=>t=>`(print ${Di(t)} (ternary ${Di(` •`)} "" ${kP(yte(e))}))`,bte=e=>vte(e).flatMap(e=>[wte(e),...e.help,...e.submenus.map(e=>Si(SP(e),TP(e),$P(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(zP.flatMap(e=>[e.sessionKey,e.configKey]));const VP=wN(oP,{arm:`⟲`,confirm:`⟲ reset all?`},zP.map(e=>({action:tP(e.name),when:e.shown}))),xte=[`unsaved`,`history.undo`,`history.redo`],HP=e=>`${P}${e}`,UP=HP(`unsaved`),WP=(e,t)=>({body:t,shown:`(gt .${HP(e)} 0)`}),GP=[WP(`unsaved`,`{{ action "${XN}" (printf "💾 save %d" .${UP}) }}`),WP(`history.undo`,`{{ action "${cP}" "↶" }}`),WP(`history.redo`,`{{ action "${mP}" "↷" }}`),{body:VP.template,shown:`(or ${kP(zP)} ${VP.armed})`}],Ste={when:`{{ or ${GP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+GP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},KP=[{step:VP,place:`door`},{step:HN,place:`session`}],qP=e=>e.map(e=>e.step.disarm),JP=qP(KP),Cte=qP(KP.filter(e=>e.place!==`door`));function wte(e){let t=$N(e.name);return e.control.kind===`inline`?GN(t):Si(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>GN(DP(e.name,n)))},`drop`)}function YP(e){return e===Li}function XP(e){let t=GN(Li);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[XP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function Tte(e){return ZP(e)>0?e:XP(e)}function ZP(e){let t=0;for(let n of Wy(e))n.kind===`segment`&&YP(n.name)&&(t+=1);return t}function QP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&YP(e.name)||e.opens!==void 0&&QP(e.opens.body,!0):e.children.some(e=>QP(e,n))}const Ete={door:{direction:`horizontal`,content:[GN(fP)],after:[GN(RN),GN(XN)]},session:{direction:`vertical`,content:[GN(zN),{kind:`container`,direction:`horizontal`,children:[GN(VN),GN(UN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[GN(ZN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[GN(hP),...ZM.map(e=>GN(yP(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[GN(nP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function $P(e){let{direction:t,content:n,after:r}=Ete[e];return{kind:`container`,direction:t,children:[...n,...bte(e),...r]}}function eF(e){return e.kind===`segment`?YP(e.name)?{kind:`container`,direction:`horizontal`,children:[Si(e.name,zi,Ote,`above`),GN(IP)]}:e:kte(e)}function Dte(){return{kind:`container`,direction:`vertical`,children:[$P(`door`),{kind:`container`,direction:`horizontal`,children:GS.map(({member:e})=>Si(qN(e),YN(e),$P(e),`drop`))}]}}const Ote=Dte();function kte(e){return{...e,children:e.children.map(e=>eF(e))}}function Ate(e){let t={variables:{[Li]:Oi(Li,gi),[Bi]:{kind:`state`,key:Bi,default:`0`}},actions:{[sP]:ki(Li,Ri),[Bi]:{set:Bi,int:!0},[Li]:{do:[sP,...JP]},[gP]:{doctor:`run`},...BN.actions,...HN.actions,...WN.actions,[XN]:{save:!0},[cP]:{undo:!0},[uP]:{back:!0},[lP]:{do:[uP,...JP]},[mP]:{redo:!0},[ZN]:{preset:`save`},[nP]:{themeDefault:`save`},[QN]:{preset:`delete`,name:`{{ .${Mx.preset.effectiveVar} }}`}},segments:{[Li]:{template:`{{ $door := ${Ei(Li,Di(e),Di(`✖`))} }}{{ if ${wi(zi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+FP},[IP]:{template:LP},[zN]:{template:BN.template},[VN]:{template:HN.template,when:HN.when},[UN]:{template:WN.template,bg:WN.bg,when:WN.when},[fP]:pP,[XN]:Ste,[nP]:aP,[ZN]:{template:`{{ action "${ZN}" "+ preset" }}`},[hP]:{template:`{{ action "${gP}" "🩺 doctor" }}`},[RN]:{template:`{{ action "${Bk}" "✎ arrange" "✎ done" }}`}}};t.variables[rP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[iP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[dP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of xte)t.variables[HP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[KN]=Oi(KN,gi);for(let{member:e,label:n}of GS){t.actions[JN(e)]=ki(KN,e),t.actions[qN(e)]={do:[JN(e),...Cte]};let r=BP(e);t.segments[qN(e)]={template:`{{ ${Ei(qN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,HN.variables,VP.variables),Mte(t),jte(t),t}function jte(e){for(let t of ZM){let n=nN(t.name),r=_P(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?aM:[];for(let n of i)e.actions[vP(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${vP(t.name,e)}" "${bP[e]}" }}`).join(``);e.segments[yP(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} "${My}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function Mte(e){for(let t of zP){Object.assign(e.actions,t.control.actions);let n=tP(t.name);e.actions[n]={reset:t.configKey},e.variables[OP(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${OP(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[$N(t.name)]={template:`${t.control.template}${RP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[DP(t.name,r)]=n})}Object.assign(e.actions,VP.actions),Object.assign(e.variables,jP.variables),Object.assign(e.actions,jP.actions),Object.assign(e.segments,jP.segments);for(let t of JS){let n=TP(t);e.actions[CP(t)]=ki(n.key,n.member),e.segments[SP(t)]={template:`{{ action "${CP(t)}" ${BP(t)(qS[t].trigger)} }}`}}}function Nte(e){let{variables:t,actions:n}=Yk();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Pte(e){let t=Ate(e.globals.menuGlyph??`🍫`);Nte(t);let n={...e.presets};for(let t of hS(e.presets)){let{node:r}=vS(e,t),i=eF(Tte(r));n[t]={..._S(e.presets,t),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const tF=`${Pi}live`,Fte=[`☐ live`,`☑ live`],nF=`${Pi}done`,rF=`${Pi}cancel`,iF=`${Pi}rewind`,aF=`${Pi}changes`,oF=`(gt .${aF} 0)`,Ite=`(or ${oF} (gt .${UP} 0))`,sF={variable:tF,key:tF,member:_i};function cF(e){return`${Pi}configuring.p${e}`}function lF(e){return`and ${wi(Wk)} (not ${wi(sF)}) (ne .${cF(e)} "true")`}function Lte(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${zk} "${xi(e)}")`).join(` `)} false }}`}}function uF(e,t,n){return`{{ if ${lF(e)} }}${t}{{ else }}${n}{{ end }}`}const Rte=`{{ and ${wi(Wk)} .preset.customized }}`,dF=Ii;function fF(e){return new Map([...qee(e),...zte(e)])}const pF=`${Pi}addable`;function zte(e){return new Map([[pF,{members:Object.keys(e.segments).filter(e=>!dF(e)),library:{groups:zC.map(e=>({id:e,label:BC[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function mF(e,t,n){return n.segments[e]={template:t,when:Gk,bg:Qk},{kind:`segment`,name:e}}function Bte(e,t,n){let r=`${Pi}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Ov}`}) (action "${r}" "✖") }}`}function hF(e){return`{{ if ${wi(Wk)} }}${e}{{ end }}`}function gF(e,t){return e.reduce((e,t)=>`{{ if and ${wi(Wk)} ${wi(t)} }}true{{ else }}${e}{{ end }}`,t)}function Vte(e){return e.flatMap(e=>[...Wy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function Hte(e,t,n){return`${Hk}${e}.${t}.${n}`}function Ute(e,t,n,r){let i=By(n),a=`${Pi}${e.presetIdent}`,o=Uk(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=jS(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:gi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:zk,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=Hte(e.presetIdent,i,r),l=`${Hk}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:ub(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=US(VS(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 Si(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${iA}" }}`,ref:{variable:zk,key:zk,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const _F=`${Pi}label:`;function vF(e){if(e.startsWith(_F)){let t=e.slice(_F.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Wte(e,t,n,r){let i=By(e),a=yF(n,i,e,t,i),o=Object.fromEntries(ab.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Si(a,r.ref,r.body,`drop`,gF([r.ref],`{{ ${lF(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(ab.map(e=>[e,r.drafts[e]]))}}function yF(e,t,n,r,i){let a=`${_F}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${xi(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function Gte(e,t,n,r){let i=By(e),a=n?[bF(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=bF(r,o,i,`after`),c=Bte(r,o,i),l=r.segments[e.name],u=Ute(r,o,e,ob(l)),d=hF(c),f=hF(u.term);return[...a.map(e=>mF(e.host,e.template,r.artifacts)),{...Wte(e,l,r,u),lead:d,trail:f},{...t,when:uF(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},mF(s.host,s.template,r.artifacts)]}function Kte(e){return E.join(E.basename(E.dirname(e)),E.basename(e))}function qte(e,t,n,r){let i=r.segments[e.name],a=By(e);return[{kind:`segment`,name:yF(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${Kte(t.file)} ${t.entry}`),when:`{{ ${lF(r.presetIdent)} }}`},{...n,when:uF(r.presetIdent,`false`,e.when??`true`)}]}function bF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Pi}${i}.insert.${t}`,s=`${Pi}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:pF,anchor:n,relation:r};let c=kS(o),l=AS(s,o,void 0),u=NS(l),d=MS(l,c);return a.variables[l]={...Oi(l,gi),within:[Wk]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ki(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${wi({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Ov}`}) $m }}{{ end }}`}}function xF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!dF(e.name)&&e.insertedBy===void 0),i=e=>xF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Uy(o,i);if(dF(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?Gte(o,s,a===r,t):qte(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:gF(Vte(n),uF(t.presetIdent,`true`,e.when))}}}function Jte(e,t,n,r,i,a,o){let s=`${Pi}${t}.resetLayout`,c=`${Pi}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Rte},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},SF(e,o)]}}function SF(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),SF(n,t)]}:{...e,children:[...e.children,t]}}function Yte(e,t,n,r,i,a){let{node:o}=vS(e,t),s={presetIdent:OS(t),rootKey:MC(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=xF(o,s);return n.variables[cF(s.presetIdent)]=Lte(s.configured),Jte(c,s.presetIdent,s.rootKey,n,r,i,a)}function Xte(e){let t={variables:{},actions:{},segments:{}},n=Xk(`${Pi}help`,cA,[Wk],t);t.variables[tF]=Oi(tF,gi),t.actions[tF]=ki(tF,sF.member),t.segments[tF]={template:Ti(tF,...Fte),when:Gk};let r={kind:`segment`,name:tF},i=n;t.variables[aF]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[nF]={do:[XN,Bk]},t.segments[nF]={template:`{{ if ${Ite} }}{{ action "${nF}" "✓ save" }}{{ else }}{{ action "${nF}" "✓ done" }}{{ end }}`,when:Gk},t.actions[iF]={rewind:!0},t.actions[rF]={do:[iF,Bk]},t.segments[rF]={template:`{{ action "${rF}" "↩ cancel" }}`,when:`{{ and ${wi(Wk)} ${oF} }}`};let a=[{kind:`segment`,name:nF},{kind:`segment`,name:rF}],o={...e.presets};for(let n of hS(e.presets)){let s=Yte(e,n,t,a,r,i);o[n]={..._S(e.presets,n),root:s}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function CF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Zte(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 Qte(e,t,n){let r=Hy(e,new Set(n.map(Vy).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const wF=/^-?\d+$/;function $te(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 ene(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 tne(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 nne(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 rne(e){return e===`config`?`set-config`:`set-state`}function ine(e,t,n){return t.kind===`int`?ene(`menu page "${e}"`):t.kind===`range`?tne(t.min,t.max,`${n} stepper "${e}"`):$te(t.allowed,`${n} "${e}"`,rne(n))}function TF(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:nne(e,n,t)}))}function EF(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 TF(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,ine(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 DF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};EF(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=EF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function ane(){return DF({},`config`,lne)}function one(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:ES(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:[CF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[CF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:ES(e.insertSegmentFrom,t).members.map(t=>CF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function sne(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?IC(n.persist):null;e?.scope===`preset-root`&&t.add(MC(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function cne(e){let t=fF(e);return[...sne(e),...Object.values(e.actions).flatMap(e=>one(e,t))]}function lne(e){return TF(cne(e),`config`)}const OF=ny(),une=new Set(OF),kF=new Set(wy),AF=e=>e?une.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${OF.join(`, `)})`}:{ok:!1,reason:`theme name is required`},jF=e=>e?kF.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${wy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},MF=new Set([`1`,`true`]),NF=new Set([`0`,`false`]),PF={endcaps:jF,theme:AF,"toolbar-expanded":e=>MF.has(e)?{ok:!0,value:`1`}:NF.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function FF(){return DF(PF,`state`,zF)}function IF(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:ES(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 LF(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(PF,e.key))}function RF(e){let t=fF(e);return LF(Object.values(e.actions).flatMap(e=>IF(e,t)))}function zF(e){return TF(RF(e))}function BF(e){let t=FF(),n=ane();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const VF=`update.dismissed`,HF=`updateNotice`,UF=Mx.updateNotice.sessionKey;function WF(){return BF({config:[{key:HF,allowed:[`false`]}],state:[{key:UF,allowed:[`false`]},{key:VF,allowed:[]}]})}function GF(e){try{return s.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const KF=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function qF(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*JF(e){let t=[];YF(e,(e,n)=>(t.push([n,e]),e)),yield*t}function YF(e,t){if(`copy`in e)return{...e,copy:t(e.copy,`copy`)};if(`open`in e)return{...e,open:t(e.open,`open`)};if(`preset`in e&&e.preset===`delete`)return{...e,name:t(e.name,`name`)};if(`run`in e){let n=e.run.map((e,n)=>t(e,`run.${n}`));return{...e,run:n,env:Object.fromEntries(Object.entries(e.env).map(([e,n])=>[e,t(n,`env.${e}`)]))}}return e}function XF(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function ZF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{},...Dk},segments:eI(t.segments,QF(t.segments,e.segments??{})),root:oS(e.root??$x,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:eI(t.presets,$F(t.presets,e.presets??{})),themeDefaults:eI(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function QF(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function $F(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 eI(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const tI=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`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function nI(e){let t=tI.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)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function rI(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(rI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(rI)}default:return!1}}function iI(e){if(Array.isArray(e))return Object.freeze(e.map(iI));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]=iI(r);return Object.freeze(t)}return e}function aI(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 oI(e){return typeof e==`string`?e:String(e)}function sI(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 cI(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 lI=class extends Error{constructor(e,t){super(t),this.variable=e}};function uI(e){return e instanceof lI?e:e instanceof Error&&e.cause!==void 0?uI(e.cause):void 0}function dI(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: ${Xy.join(`, `)})`,line:q(e.source,t.split(`.`))}),null):mI(e,`${t}.cache`,n.cache)}function fI(e){return{required:!0,json:hI(),parse:(t,n,r,i)=>dI(t,n,i,e)??void 0}}const pI={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&_I(n)?{ttl:n}:Eb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${J(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Eb(e,t,`cache.watch_file must be a path string, got ${J(n)}`);let r=Nb(`cache.watch_file`,n);return r===null?{watch_file:n}:Eb(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}:Eb(e,t,`cache.depends_on must be an array of variable-name strings, got ${J(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Eb(e,t,`cache.key must be a non-empty template string, got ${J(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Eb(e,t,`cache.never must be the literal boolean true, got ${J(n)}`)}}};function mI(e,t,n){return Db(e,pI,t,n)}function hI(){return Bb(pI)}const gI=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function _I(e){return gI.test(e)}const vI=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 yI(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 bI(e){let t=vI.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${yI(t)}`}function xI(e){let t=vI.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${yI(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const SI=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),CI=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function wI(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function TI(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?CI.get(e.field):void 0;if(n===void 0){let e=[...CI.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${wI(n.declare)} under a name of your own`}function EI(e,t,n){if(n===void 0)return{};if(!bb(n))return e.issues.push({path:t,message:`${t} must be an object, got ${xb(n)}`,line:q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=zee(e,YI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function DI(){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 ${xb(i)}`,line:q(e.source,t.split(`.`))});return}return i}}}function OI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Lee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const kI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Eb(e,t,`parse.text must be the literal boolean true, got ${J(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?AI(e,t,n):Eb(e,t,`parse.regex must be a pattern string, got ${J(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Eb(e,t,`parse.json must be the literal boolean true, got ${J(n)}`)}}};function AI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Eb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Eb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function jI(){return{required:!1,json:Bb(kI),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:q(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Db(e,kI,`${t}.parse`,r.parse)??void 0)}}function MI(){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)=>bb(r.parse)&&`json`in r.parse?NI(e,t,r.default):_b(e,t,r,`default`)}}function NI(e,t,n){if(n!==void 0)return PI(n)?n:Eb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${J(n)}`)??void 0}function PI(e){return e!==null&&rI(e)}const FI={value:DI(),default:kb()};function II(){let e=Mb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:SI.get(a);return o===void 0?a:Eb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const LI={path:II(),type:Fb([`string`,`number`,`boolean`]),default:OI()},RI={name:Mb(),default:kb()},zI={path:Pb(),readMode:Fb([`whole`,`first-line`]),parse:jI(),cache:fI(`file`),default:MI()},BI={command:Mb(),parse:jI(),cache:fI(`shell`),default:MI()};function VI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const HI={template:Mb(),type:Fb([`string`,`number`,`boolean`]),default:OI()},UI=VI(`a template variable recomputes whenever a variable it reads changes`),WI={layout:Mb(),default:kb()},GI=VI(`a time variable reads the instant its render is drawn at`),KI={key:Mb(),default:kb()},qI=`kind`;function JI(e,t,n={}){return{...Bee(qI,e,t),parse:(r,i,a)=>{Cb(r,n,i,a);let o=wb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const YI={tag:qI,noun:`source kind`,memberNoun:`variable`,arms:{literal:JI(`literal`,FI),input:JI(`input`,LI),env:JI(`env`,RI),file:JI(`file`,zI),shell:JI(`shell`,BI),template:JI(`template`,HI,UI),time:JI(`time`,WI,GI),state:JI(`state`,KI)},retired:{git:TI}};function XI(){return zb(YI)}function ZI(){return{type:`object`,additionalProperties:XI()}}const QI=/^[A-Za-z_][A-Za-z0-9_]*$/,$I={pattern:QI.source},eL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},tL={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`,...$I}}}]},default:eL}},nL=[`label`,`domain`,`default`],rL=[`min`,`max`,`step`,`atLeast`];function iL(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function aL(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 iL(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 iL(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?iL(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(bb(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!rL.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}}:iL(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 iL(e,t,`domain must be "bool", a list of words, or { min, max }, got ${J(n)}`)}function oL(e,t,n){if(!bb(n))return iL(e,t,`${t} must be { label, domain, default }, got ${xb(n)}`);for(let r of Object.keys(n))nL.includes(r)||iL(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${nL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||iL(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${J(r)}`);let a=aL(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!sL(n.default)||!lb(o,n.default)?iL(e,`${t}.default`,`default must be ${fb(o)}, got ${J(n.default)}`):o}function sL(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const cL={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${rb}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function lL(e){return ab.includes(e)}function uL(){return{required:!1,json:{type:`object`,propertyNames:{...$I,not:{enum:[...ab]}},additionalProperties:tL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!bb(i))return iL(e,a,`${a} must be an object of name → { label, domain, default }, got ${xb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!QI.test(t)){iL(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(lL(t)){iL(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${cL[t]}`);continue}let r=oL(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const dL=Fi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function fL(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${dL})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!Ii(i)?i:iL(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Fi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${J(i)}`)}}}function pL(){return{required:!1,json:{type:`object`,propertyNames:$I,additionalProperties:eL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!bb(i))return iL(e,a,`a placement's "settings" must be an object of setting name → value, got ${xb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))sL(n)?o[t]=n:iL(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${xb(n)}`);return o}}}function mL(e){return new Set(Object.keys(e.segments).filter(e=>!Ii(e)))}function hL(e,t,n){if(t===void 0)return{};if(!bb(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${xb(t)}`,line:q(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Sb(e,n.has(i)?TL:wL,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function gL(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${xb(s)}`,line:q(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${xb(i)}`,line:q(e.source,[...t.split(`.`),n])})}const _L={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function vL(){return{required:!0,json:_L,parse:(e,t,n,r)=>r[n]===void 0?Eb(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${nI(t.slice(9))}`)??void 0:gL(e,t,n,r)}}function yL(){return{required:!1,json:_L,parse:(e,t,n,r)=>r[n]===void 0?void 0:gL(e,t,n,r)}}function bL(){return{required:!1,json:{type:`object`,additionalProperties:_L},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!bb(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${xb(i)}`,line:q(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=gL(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function xL(){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 ${J(i)}`,line:q(e.source,[...t.split(`.`),n])})}}}}function SL(){return{required:!1,json:ZI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return EI(e,`${t}.${n}`,i)}}}const CL={template:vL(),description:kb(),group:Fb(RC),width:xL(),justify:Fb(Dee),truncate:Fb(Oee),bg:kb(),fg:kb(),when:kb(),palette:Uee(),vars:SL(),settings:uL(),missingData:Fb(eb),partials:bL()},wL={noun:`segment key`,fields:CL},TL={noun:`segment key`,fields:{...CL,template:yL()}};function EL(e,t){if(t===void 0)return{};if(!bb(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${xb(t)}`,line:q(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 ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function DL(e,t,n){if(t===void 0)return{};if(!bb(t))return Y(e,`actions`,`actions must be an object, got ${xb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=OL(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Y(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function OL(e,t,n,r){if(!bb(n))return Y(e,t,`${t} must be an action object, got ${xb(n)}`),null;if(`persistWhen`in n)return Y(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 i=KF.filter(e=>e in n);return i.length===1?AL(r)[i[0]](e,t,n):(Y(e,t,`action must declare exactly one of: ${KF.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function kL(e){return e===`<default>`?{dir:null}:E.isAbsolute(e)?{dir:E.dirname(e)}:{text:e}}const AL=e=>({set:(e,t,n)=>fR(e,t,n,`set`,cR),persist:(e,t,n)=>fR(e,t,n,`persist`,lR),copy:jL(`copy`),open:jL(`open`),reset:ML,undo:PL(`undo`),redo:PL(`redo`),back:PL(`back`),rewind:PL(`rewind`),save:PL(`save`),preset:FL,themeDefault:IL,doctor:RL,slash:zL,run:HL(e),do:UL});function jL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Y(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=gb(t,n,r,e);return i===null?null:{[e]:i}}}function ML(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=WL(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 NL={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 PL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Y(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Y(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${NL[e]}), got ${J(r[e])}`),null)}}function FL(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Y(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Y(e,`${t}.preset`,`preset must be "save" or "delete", got ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=gb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function IL(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Y(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${J(n.themeDefault)}`),null)}const LL={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function RL(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(LL,r),a=i?LL[r]:[...new Set(Object.values(LL).flat())];for(let r of Object.keys(n))a.includes(r)||Y(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Y(e,`${t}.doctor`,`doctor must be ${Object.keys(LL).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?QM:ZM;if(typeof o!=`string`||!s.some(e=>e.name===o))return Y(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return aM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Y(e,`${t}.mark`,`doctor mark must be ${aM.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function zL(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=EN(n.slash);return r.kind===`refused`?(Y(e,`${t}.slash`,r.reason),null):{slash:r.line}}const BL=[`run`,`env`,`refreshes`],VL=/^[A-Za-z_][A-Za-z0-9_]*$/;function HL(e){return(t,n,r)=>{for(let e of Object.keys(r))BL.includes(e)||Y(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${BL.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Y(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${J(a)}`);let o=r.env??{};(!bb(o)||Object.entries(o).some(([e,t])=>!VL.test(e)||typeof t!=`string`))&&Y(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${J(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Y(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${J(s)}`),`dir`in e||Y(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}VL.source;function UL(e,t,n){for(let r of Object.keys(n))r!==`do`&&Y(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===``)?(Y(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 ${J(r)}`),null):{do:r}}function WL(e,t,n,r,i,a){let o=gb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Y(e,s,i),null):o.includes(`/`)?(Y(e,s,a(o)),null):o}const GL={set:`the SessionState key to write`,persist:`the config globals field to write`};function KL(e,t,n,r){let i=GL[r],a=WL(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 qL(e){return e===`set`?`set-state`:`set-config`}const JL={to:pR(`set`)},YL={to:pR(`persist`)},XL={from:mR(`set`)},ZL={from:mR(`persist`)},QL={min:yR(),max:yR(),by:yR()},$L={int:gR()},eR={cycle:hR(`set`)},tR={cycle:hR(`persist`)},nR={removeSegment:_R(`removeSegment`)},rR={insertSegment:_R(`insertSegment`),anchor:_R(`anchor`),relation:vR()},iR={insertSegmentFrom:mR(`persist`),anchor:_R(`anchor`),relation:vR()},aR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},oR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function sR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>wb(e,t,n,r),c=Ib(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?Vee(s,...n):s}}const cR=[sR(`set`,JL),sR(`set`,XL),sR(`set`,QL,[aR,oR]),sR(`set`,$L),sR(`set`,eR)],lR=[sR(`persist`,YL),sR(`persist`,ZL),sR(`persist`,QL,[aR,oR]),sR(`persist`,tR),sR(`persist`,nR),sR(`persist`,rR,[],[`insertSegment`]),sR(`persist`,iR,[],[`insertSegmentFrom`])];function uR(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=uR(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 fR(e,t,n,r,i){let a=KL(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Y(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)||Y(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 pR(e){let t=qL(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>WL(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 mR(e){let t=qL(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===``){Y(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){Y(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===``)){Y(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){Y(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){Y(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Y(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${J(o)}`)}}}function hR(e){let t=qL(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`)){Y(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${xb(o)}`);return}let c=o;if(c.length<2){Y(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){Y(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Y(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){Y(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function gR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Y(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${J(r[n])}`);return}return!0}}}function _R(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=gb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Y(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Y(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 vR(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Y(e,`${t}.${n}`,`relation must be "before" or "after", got ${J(i)}`);return}return i}}}function yR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Y(e,`${t}.${n}`,`${n} must be an integer, got ${J(i)}`);return}return i}}}const bR=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*xR(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2,i=[[0,r]];for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2,i.push([n.length,r]);continue}let t=r,a=e[r];if(r+=1,a===`"`||a===`'`||a==="`"){for(;r<e.length&&e[r]!==a;)r+=e[r]===`\\`&&a!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield{text:n,at:e=>{let[t,n]=i[0];for(let[r,a]of i)r<=e&&([t,n]=[r,a]);return n+e-t}},t=e.indexOf(`{{`,r+2)}}const SR=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,CR=RegExp(`^(?:(\\$)(?:\\.(${SR}))?|\\.(${SR})?)(?=[\\s)]|$)`);function wR(e,t,n){let r=CR.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 TR=/^(\w+)\b\s*([\s\S]*)$/;function*ER(e,t){let n=[t];for(let r of xR(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=TR.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,block:r};let i=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=i===null?s:wR(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(wR(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const DR=/(?<![.$])\btemplate\s+$/;function*OR(e,t,n){let r=0;for(let i of[...e.matchAll(bR)]){let a=i.index+i[0].length;DR.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:wR(e.slice(a),t,n),index:i.index}),r=a}}function*kR(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...ER(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...OR(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)}function AR(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const jR=new WeakMap;function MR(e,t){let n=jR.get(t);return n===void 0&&(n=AR(e=>[...kR(e,t)]),jR.set(t,n)),n(e)}const NR=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${SR})`,`g`);function*PR({code:e,dot:t,root:n}){let r=e.replace(bR,``);for(let e of[...r.matchAll(NR)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function FR(e,t){let n=new Map;for(let r of MR(e,t))for(let e of PR(r))n.has(e)||n.set(e,r.via);return n}const IR=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,LR={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*RR(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(bR)]){let a=e.slice(t,i.index),o=IR.exec(a);o===null?a.trim()!==``&&(n=0):(n=LR[o[1]],r=o[1]===`action`?`action`:`options`),n>0&&(yield{name:i[0].slice(1,-1),site:r,index:i.index},n--),t=i.index+i[0].length}}function zR(e,t){let n=new Map;for(let{code:r,via:i}of MR(e,t))for(let{name:e,site:t}of RR(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const BR=e=>Object.keys(LR).filter(t=>LR[t]>=e).join(`|`),VR=RegExp(`(?<![\\w.$])(?:(?:${BR(1)})\\s+|(?:${BR(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function HR(e,t){for(let{code:n}of MR(e,t))if(VR.test(n.replace(bR,`""`)))return!0;return!1}const UR=/(?<![\w.$])[A-Za-z_]\w*/g;function WR(e,t){let n=new Set;for(let{code:r}of MR(e,t))for(let[e]of r.replace(bR,``).matchAll(UR))n.add(e);return n}function GR(e,t){return new Set([...KR(e,t)].filter(e=>Object.hasOwn(t,e)))}function KR(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of MR(e,t))for(let{name:e}of OR(r,i,a))n.add(e);return n}const qR=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function JR(e,t,n){let r=qR(t),i=yk(t),a=[];for(let{dot:t,block:n}of ER(e,``)){let e=n.text.replace(bR,e=>` `.repeat(e.length));for(let i of e.matchAll(r))(i[1]===`$`?``:t)===``&&a.push(n.at(i.index+i[1].length+1));for(let{name:e,index:r}of[...OR(n.text,t,``),...RR(n.text)])i(e)&&a.push(n.at(r+1))}return[...new Set(a)].sort((e,t)=>t-e).reduce((e,r)=>e.slice(0,r)+n+e.slice(r+t.length),e)}function*YR(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*XR(e){for(let[t,n]of YR(e))yield[t,n]}function ZR(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function QR(e,t){return ZR(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function $R(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),ez(r)&&n.add(e)};for(let[t,n]of XR(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function ez(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&Yy(e.parse)===`json`}function tz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const nz=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),rz=`plugin.json5`,iz=/^[a-z][a-z0-9_]*$/;function az(e,t){let n=E.basename(E.dirname(e));return iz.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function oz(e){return`${e}.data`}function sz(e){return`${e}.json`}function cz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:lz(e)}}}function lz(e){return e instanceof pb?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 uz(e,t,n,r){return e.map(e=>az(pA(E.dirname(t),e,r),n))}function dz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:vk(n),c=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(E.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${rz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${rz} and list that`;return c(t,o===void 0?e.config:pz(fz(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${E.basename(E.dirname(a))}" is not a plugin name (one matching ${iz}: it prefixes every name the plugin declares)`,e.config);let l=i.get(o);if(l!==void 0)return c(`plugin "${n.name}" is already listed, from ${l}`,e.config);i.set(o,a);let u=fz(e.config,o),d=cz(()=>{let i=s.readFileSync(a,`utf-8`),c=ZF(yz(a,n,{source:i,json:Ia.default.parse(i)},t),u);return Pz(a,o,c),r(c,o,u!==e.config),c});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={...n,reason:d.reason};return c(d.reason,pz(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function fz(e,t){let n=yk(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 pz(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:tz(n),definition:n.path}}}}function mz(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>yk(t)(e))}function hz(e,t){let n=mz(e.config),r=[...e.rendering.keys()].map(yk),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=xk(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:tz(e)})):[{definition:a.definition,notice:a.notice}]}}function gz(e,t,n){let r=hS(e.presets).flatMap(t=>[...Wy(vS(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,_z(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=mz(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...Cz.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>zR(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...KR(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function _z(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,vz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function vz(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 yz(e,t,{source:n,json:r},{checkout:i,home:a}){let o=vk(t),c=[],l=()=>{throw new pb(e,c)};if(!bb(r))return c.push({path:``,message:`a plugin definition must be an object, got ${xb(r)}`}),l();for(let t of Object.keys(r))nz.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${E.basename(E.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...nz].join(`, `)}`});let u=r.data===void 0?void 0:Lz(r.data,e,i,a,c),d=r.sources===void 0?{}:Nz(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(ny()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:EI(f,`data`,{[oz(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=EI(f,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(d)]])t.includes(`data`)&&c.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${oz(o)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(d))Object.hasOwn(m,e)&&c.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let h={variables:{...p,...Ez(o,d),...Ez(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,Oz(o,t)])))},segments:Ez(o,kz(o,hL(f,r.segments,new Set))),helpers:Ez(o,EL(f,r.helpers)),actions:Ez(o,Az(o,DL(f,r.actions,{dir:s.realpathSync(E.dirname(e))})))};c.push(...wz(h,t));let g=bz(o,h);for(let[e,t]of Tz(g))try{gk.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),g}function bz(e,t){let n=t=>JR(t,bk,e),r=t=>yk(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>xz(Qy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(Cz.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>xz(Qy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>Sz(YF(e,n),r))}}function xz(e,t){return Zy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function Sz(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const Cz=[`template`,`bg`,`fg`,`when`];function wz(e,t){let n=e.helpers??{},r=_k.filter(e=>e!==t.scope).map(e=>({scope:e,ns:vk({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>yk(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${vk(t)}: a plugin names itself without its scope — write ${s}${bk}${n.slice(o.ns.length)}`})},o=[...[...Tz(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of FR(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of zR(t,n))i===null&&a(e,r,!1);for(let n of KR(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))Sz(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(Zy(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*Tz(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of $y(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of Cz){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of $y(r))yield[`segments.${t}.vars.${e}.${n}`,i]}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??{}))for(let[e,r]of JF(n))yield[`actions.${t}.${e}`,r]}function Ez(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function Dz(e,t){return`${e}.${t}`}function Oz(e,t){return t.kind===`state`?{...t,key:Dz(e,t.key)}:t}function kz(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,Oz(e,n)]))}]))}function Az(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Dz(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>Dz(e,t))}:n]))}const jz=iz,Mz={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function Nz(e,t,n){if(!bb(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${xb(e)}`}),{};let r=E.join(s.realpathSync(E.dirname(t)),`session`),i=JSON.stringify(Mz),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!jz.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${jz}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=Iz(o,Mz,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function Pz(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=Fz(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=yk(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new pb(e,a)}function Fz(e){return E.join(e.storage,sz(`<session id>`))}function Iz(e,t,n){return!bb(t)||!bb(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?Iz(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function Lz(e,t,n,r,i){if(typeof e==`string`&&e!==``)return pA(E.dirname(t),e,r);if(bb(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(E.isAbsolute(t)||t.startsWith(`~`)||E.normalize(t).split(E.sep)[0]===`..`){i.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){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return E.resolve(n.root,t)}if(bb(e)&&`project`in e){i.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}i.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 Rz(e,t){let n=[...[...e.dataDirs].reverse().map(e=>E.join(e,`cc-candybar`,`plugins`)),zz(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:E.join(t,Bz),scope:`repo`}]]}function zz(e){return E.join(e.dataHome,`cc-candybar`,`plugins`)}const Bz=E.join(`.cc-candybar`,`plugins`);function Vz(e,t){let n=Rz(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=Hz(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=az(E.join(e,i,rz),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:E.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${rz}: move this file to ${E.join(e,`<name>`,rz)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function Hz(e){try{let t=s.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()||Uz(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 Uz(e,t){if(!t.isSymbolicLink())return!1;try{return s.statSync(E.join(e,t.name)).isDirectory()}catch{return!0}}function Wz(e){return s.existsSync(E.join(e,`.git`))}function Gz(e){let t=E.resolve(e);for(;;){if(Wz(t))return t;let e=E.dirname(t);if(e===t)return;t=e}}function Kz(e){let t=Gz(e);return t===void 0?{root:E.resolve(e),git:!1}:{root:t,git:!0}}function qz(e){try{return F(e())}catch(e){return e.code===`ENOENT`?I:L(e.message,`read`)}}const Jz=e=>qz(()=>s.realpathSync.native(e)),Yz=(e,t)=>t.kind===`absent`?`${e} is not there`:t.reason;function Xz(e){let t=qz(()=>s.readFileSync(E.join(e,`.git`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();return n===void 0?L(`${E.join(e,`.git`)} names no gitdir`,`parse`):F(E.resolve(e,n))}function Zz(e){let t=qz(()=>s.readFileSync(E.join(e,`commondir`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.trim();return n===``?L(`${E.join(e,`commondir`)} is empty`,`parse`):F(E.resolve(e,n))}const Qz={kind:`unlinked`},$z=e=>({kind:`unproven`,reason:e});function eB(e){let t=Gz(e);if(t===void 0)return Qz;let n=E.join(t,`.git`),r=qz(()=>s.statSync(n));if(r.kind===`ok`&&r.value.isDirectory())return Qz;let i=qz(()=>s.lstatSync(n));if(i.kind!==`ok`)return $z(Yz(n,i));if(!i.value.isFile())return $z(`${n} is not a file`);let a=Xz(t);if(a.kind!==`ok`)return $z(Yz(n,a));let o=Jz(a.value);if(o.kind!==`ok`)return $z(Yz(a.value,o));let c=Zz(o.value);if(c.kind===`absent`)return Qz;if(c.kind===`failed`)return $z(c.reason);let l=Jz(c.value);if(l.kind!==`ok`)return $z(Yz(c.value,l));if(E.dirname(o.value)!==E.join(l.value,`worktrees`))return $z(`${o.value} is not a worktree of ${l.value}`);let u=E.join(o.value,`gitdir`),d=qz(()=>s.readFileSync(u,`utf-8`));if(d.kind!==`ok`)return $z(Yz(u,d));let f=E.resolve(o.value,d.value.trim()),p=Jz(E.dirname(f));if(E.basename(f)!==`.git`||p.kind!==`ok`||p.value!==t)return $z(`${o.value} is the worktree at ${f}, not ${t}`);let m=E.basename(l.value)===`.git`?E.dirname(l.value):l.value;return{kind:`linked`,main:E.join(m,E.relative(t,e))}}function tB(e){let t=Jz(e),n=t.kind===`ok`?t.value:E.resolve(e),r=Gz(n);if(r===void 0)return{main:``,worktree:``,subpath:``,noRepo:!0};let i=E.relative(r,n),a=i===``?``:`/${i.split(E.sep).join(`/`)}`,o=eB(n);return o.kind===`linked`?{main:E.resolve(o.main,E.relative(n,r)),worktree:E.basename(r),subpath:a,noRepo:!1}:{main:r,worktree:``,subpath:a,noRepo:!1}}const nB=[`approved`,`declined`];function rB(e){return e.link.kind===`linked`?e.link.main:e.dir}const iB=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function aB(e,t){let n=rB(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=iB(e.value,n),i=iB(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function oB(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...aB(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&aB(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function sB(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function cB(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!nB.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${nB.join(` or `)}`};return{kind:`ok`,value:e}}function lB(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function uB(e){let t=lB(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const dB=[`json5`,`json`];function fB(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?dB.map(e=>E.join(t,`${pB}.${e}`)):[],...dB.map(e=>E.join(i,`${pB}.${e}`)),...dB.map(t=>`${mB(e)}.${t}`)])]}const pB=`.cc-candybar`;function mB(e){return E.join(e.configHome,`cc-candybar`,`config`)}function hB(e){return{path:e,scope:`plugins`}}function gB(e,t,n,r,i){let a=[],o=new Map;for(let t of fB(e,n,r,i)){let n=GF(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=s.realpathSync.native(E.dirname(t)),c=E.join(r,E.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||_B(e,t)?null:{dir:r,link:eB(r)}})}let c=[...o.values()],l=oB(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),vB(n)),u=c.filter(e=>e.repo===null||l.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(i===void 0)return{kind:`chain`,layers:u,home:yB(e,u),unchecked:a,repos:l};let[d]=a,f=i;return u.length>0?{kind:`chain`,layers:u,home:f,unchecked:a,repos:l}:d===void 0?{kind:`missing`,path:i,home:f,repos:l}:{kind:`unreadable`,...d,home:f,repos:l}}function _B(e,t){return dB.some(n=>t===`${mB(e)}.${n}`)}function vB(e){if(e===void 0||GF(e)!==`present`)return null;let t=Hz(E.join(e,Bz)),n=s.realpathSync.native(e);return{dir:n,link:eB(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function yB(e,t){return t.find(t=>_B(e,t.path))?.path??`${mB(e)}.${dB[0]}`}function bB(e,t,n,r,i){let a=gB(e,t,n,r,i),o=a.kind===`chain`?a.layers:[];return{path:a.home,above:o.filter(e=>e.path!==a.home),repo:a.repos.plugins,cwd:r??null,locs:e}}function xB(e){return SB(e).join(`
|
|
180
|
-
`)||null}function SB(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 CB(e,t,n){let r=fB(e,t,n).filter(e=>GF(e)===`present`),i=new Map;for(let e of r){let t=E.dirname(e),n=E.basename(e).replace(/\.(json5|json)$/,``),r=E.join(t,n);i.has(r)||i.set(r,[]),i.get(r).push(e)}let a=[...i.values()].filter(e=>e.length>1);return a.length===0?null:`config-extension collision: ${a.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function wB(e,t,n,r){let i=E.join(e,t),a=()=>{let e;try{e=s.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&&Dn(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const TB={error:{rank:0,glyph:`⚠`,colors:FA},warning:{rank:1,glyph:`⚠`,colors:IA},info:{rank:2,glyph:`ℹ`,colors:LA}},EB={level:`error`,glyph:TB.error.glyph},DB={level:`warning`,glyph:TB.warning.glyph},OB={level:`info`,glyph:`⬆`},kB={level:`info`,glyph:`🔒`},AB={level:`info`,glyph:`🧪`},jB=e=>TB[e.level].colors;function MB(e,t){return{text:UA(e),link:t}}function NB(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=PB(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,EB)),...r,...i.flatMap(e=>o(e,DB))].sort((e,t)=>LB(e)-LB(t)),c=FB(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[MB(n.lines[0][0].text,IB(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function PB({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>MB(e,null)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:r,about:e,message:t,copy:n,lines:[i,...a]}]}function FB(e){return VB(e).map(e=>String(e*zB+1))}function IB(e,t,n,r){return Ta([{verb:ha,args:[e,t,n]}],`copy diagnostic ${r}`)}const LB=e=>TB[e.severity.level].rank;function RB(e){return e[0]?.severity.level??null}const zB=4096;function BB(e){let t=oe(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,9),16)%2**32}function VB(e){let t=new Map;return e.map(e=>{let n=BB(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function HB(e,t,n){return String(VB(e)[t]*zB+n+1)}function UB(e){let t=RB(e),n=e.length,{glyph:r,colors:i}=TB[t??`info`];return{label:t===null?``:`${r} ${n>9?`9+`:n}`,fg:i.fg,bg:i.bg,open:e.length===0?`0`:HB(e,0,0)}}function WB(e,t){let n=Number(e)-1,r=VB(t).indexOf(Math.floor(n/zB));return e===null||r===-1?null:{index:r+1,page:n%zB}}function GB(e,t){return Math.min(20,e??20,...t)}function KB(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=YB(i),c=QB(o,s,[]),l=jB(o.severity),u=new U({bgcolor:l.bg,color:l.fg}),d=(e,t)=>XB(e,t===null?u:u.withLink(t)),f=(t,r)=>r===null?d(` `,null):d(t,JB(n,HB(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),p=(t,i)=>{let o=i>0?{index:a,page:i-1}:a>1?{index:a-1,page:0}:null,c=i<t-1?{index:a,page:i+1}:a<e.length?{index:a+1,page:0}:null,l=e.length>1||t>1,u=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return ZB([d(`✕`,JB(n,`0`)),...l?[f(`‹`,o)]:[],d(u,null),...l?[f(`›`,c)]:[],d(`⧉ copy`,IB(n,r,HB(e,a-1,0),a))],s)},m=1;for(;;){let e=Math.max(1,i.rows-m),n=Math.min(zB,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=p(n,r);if(a.length>m){m=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,u=r===n-1&&l>0?[...o.slice(0,-1),...ZB([d(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...u]}}function qB(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=UB(t),c=i===``?[]:[XB(i,new U({bgcolor:o,color:a}).withLink(JB(n,s)))];return QB(e,YB(r),c)}function JB(e,t,n){return Ta([{verb:Wi,args:[e,Bi,t]}],n)}function YB(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const XB=(e,t)=>new K(`${e} `,{style:t,end:``,overflow:`ignore`}),ZB=(e,t)=>Tj(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function QB(e,t,n){let r=jB(e.severity),i=new U({bgcolor:r.bg,color:r.fg}),a=e=>e===null?i:i.withLink(e),o=tl(Math.max(2,t.width-1));return e.lines.flatMap((r,s)=>{let c=XB(s===0?e.severity.glyph:` `,i),l=r.flatMap(e=>e.text.split(` `).flatMap(e=>ol(e,o)).map(t=>XB(t,a(e.link)))),u=s===0?n:[];return ZB([c,...l,...u],t)})}const $B=`repo-configs.json`;function eV(e){return E.join(e,`repo-configs`)}function tV(e){return E.join(eV(e),$B)}const nV=e=>{let t=wB(eV(e),$B,{},cB),n=wB(e,$B,{},cB),r=()=>s.existsSync(tV(e));return{read:()=>(r()?t:n).read(),update:e=>{if(r())return t.update(e);let i=n.read();return i.kind===`failed`?i:t.update(()=>e(i.value))}}};function rV(e,t,n){let r={superseded:[],absent:[],unchecked:[]},i=e.update(e=>{let i=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:GF(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&rB({dir:e,link:eB(e)})===t).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},sB(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function iV(e,t,n){return{sessionId:e,action:ma,declaration:t,evaluated:n}}function aV(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=nB.map(r=>MB(`[${r===`approved`?`approve`:`decline`}]`,Ta([{verb:ma,args:[t,e,r,n.sign(iV(t,e,r))]}]))),a=[MB(r,null),...i];return{severity:kB,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function oV(e){let t=E.basename(e),n=E.dirname(e);for(;;){let r=sV(n);if(r!==null)return{dir:r,name:t,leaf:n===E.dirname(e)};t=E.basename(n),n=E.dirname(n)}}function sV(e){try{return s.statSync(e).isDirectory()?s.realpathSync(e):null}catch{return null}}const cV=(e,t)=>k(t);function lV(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=An(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=oV(t);n&&=a;let o=r.has(e)?r.get(e):new Set;o?.add(i),r.set(e,o)}}for(let t of e.whole.map(sV))t!==null&&r.set(t,null);let i={dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},a=new Map(i.dirs.map(e=>{let t=Ac(e.path);return[e.path,Mc(t)?jc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function uV(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}function dV(e,t){if(t.kind===`failed`)return t;if(e.kind!==`changed`)return e;if(t.kind===`unknown`)return t;for(let n of t.paths)e.paths.add(n);return e}const fV=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([E.join(e,t)])},pV=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),mV=(e,t)=>e.kind===`listening`&&e.handle===t,hV=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var gV=class{slots=new Map;dirs=new Map;counters;logger;clock;closed=!1;constructor(e){this.clock=e.clock,this.counters=e.counters,this.logger=e.logger??cV}acquire(e,t,n){if(this.closed)return{release:()=>{},deaf:t.dirs.map(e=>({kind:`refused`,path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);for(let{dir:e}of r?.listeners??[])this.judged(e,`acquire`);let i=r??this.opened(e,t),a={onInvalidate:n};return i.holders.add(a),this.makeHandle(i,a)}follow(e,t,n){if(e!==null&&(e.key===t.key||t.unbound))return{watch:e,move:`kept`};let r={key:t.key,handle:this.acquire(t.key,t.targets,n)};return e?.handle.release(),{watch:r,move:`rebound`}}opened(e,t){let n={key:e,listeners:[],holders:new Set,debounce:null};for(let e of t.dirs){let t=this.dirFor(e),r={slot:n,dir:t,filter:e.filenames?new Set(e.filenames):null};t.listeners.add(r),n.listeners.push(r)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind===`listening`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=hV(e),n=this.dirs.get(t);if(n!==void 0)return this.judged(n,`acquire`),n;let r={path:e.path,recursive:e.recursive===!0},i={id:t,...r,listeners:new Set,state:this.open(r,()=>i,`acquire`,null)};return this.dirs.set(t,i),i}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}let n=Ac(e.path);Mc(n)&&jc(n)!==e.state.bound&&this.reopen(e,`another folder is at its path`)}judge(){for(let e of this.dirs.values())this.judged(e,`period`)}reopen(e,t){let n=e.state;n.kind===`listening`&&this.closeHandle(e.path,n.handle,t),e.state=this.open(e,()=>e,t,n),e.state.kind===`listening`?this.tell(e,{kind:`unknown`}):n.kind===`listening`&&this.tell(e,pV(e.state.deafness))}open(e,t,n,r){let i=e.path,a=jc(Ac(i));try{s.opendirSync(i).closeSync();let r=s.watch(i,{persistent:!1,recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.on(`error`,e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!mV(n.state,r))return;this.closeHandle(i,r,`error`);let a={kind:`failed`,path:i,reason:e.message};n.state={kind:`deaf`,deafness:a},this.tell(n,pV(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${R(i)} cause=${R(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t=e.message;return r?.kind===`deaf`&&r.deafness.kind===`refused`&&r.deafness.reason===t||this.logger(`warn`,`watch failed ${i}: ${t}`),{kind:`deaf`,deafness:{kind:`refused`,path:i,reason:t}}}}heard(e,t,n){let{state:r}=e;if(!mV(r,t))return;let i=n===E.basename(e.path)&&jc(Ac(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,fV(e.path,n));i&&this.judged(e,`moved`)}tell(e,t){for(let{slot:n}of e.listeners)this.fire(n,t)}fire(e,t){if(e.debounce!==null){e.debounce.window=dV(e.debounce.window,t);return}let n={window:t,cancel:this.clock.after(50,()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${R(e.key)}: ${t.message}`)}},{unref:!0})};e.debounce=n}makeHandle(e,t){return{get deaf(){return e.listeners.flatMap(({dir:e})=>e.state.kind===`deaf`?[e.state.deafness]:[])},release:()=>{!e.holders.delete(t)||e.holders.size>0||this.slots.get(e.key)===e&&(this.closeSlot(e,`last release`),this.slots.delete(e.key))}}}closeHandle(e,t,n){try{t.close()}catch{}this.counters&&this.counters.dirWatchesClosed++,this.logger(`info`,`dir watch closed path=${R(e)} cause=${R(n)}`)}closeSlot(e,t){e.debounce!==null&&(e.debounce.cancel(),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;e.listeners.delete(n),!(e.listeners.size>0)&&(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),this.dirs.delete(e.id))}this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}};const _V=`#/definitions/LayoutNode`,vV={kind:`container`,direction:`vertical`,children:[]};function yV(e){return{required:!0,json:{const:e},parse:()=>e}}function bV(){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 ${J(i)}`,line:q(e.source,[`root`])}),``)}}}function xV(){return{required:!0,json:{enum:[...Ry]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Ry.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Ry.join(`, `)} (got ${JSON.stringify(i)})`,line:q(e.source,[`root`])}),`vertical`)}}}function SV(e){return{required:!0,json:{type:`array`,items:{$ref:_V}},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 ${xb(a)}`,line:q(t.source,[`root`])}),[])}}}const CV={noun:`layout-node key`,fields:{kind:yV(`segment`),name:bV(),when:kb(),id:fL(),settings:pL()}},wV=()=>Fb(uv),TV={noun:`layout-node key`,fields:{kind:yV(`container`),direction:xV(),children:SV(Ob(()=>AV)),when:kb(),distribution:wV()}};function EV(){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 ${J(i)}`,line:q(e.source,[...t.split(`.`),n])}),``)}}}const DV={noun:`layout-node key`,fields:{seg:EV(),when:kb(),id:fL(),settings:pL()}},OV={noun:`layout-node key`,fields:{h:SV(Ob(()=>AV)),when:kb(),distribution:wV()}},kV={noun:`layout-node key`,fields:{v:SV(Ob(()=>AV)),when:kb(),distribution:wV()}},AV=(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:q(e.source,[`root`])}),vV):{kind:`segment`,name:n};if(!bb(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 ${xb(n)}`,line:q(e.source,[`root`])}),vV;if(n.kind===`container`)return Sb(e,TV,t,n)??vV;if(n.kind===`segment`)return Sb(e,CV,t,n)??vV;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
179
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${hM[e]}`)]}}const yM={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=_M(e),n=lM(vM(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},bM="re-run `cc-candybar install`";function xM(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:// — ${bM}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${bM}`]}const SM={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.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${bM}`};case`lost`:return lM([...xM(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 CM({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 wM(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Ub.join(`|`)}>\``:e.checkout===null?bM:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function TM(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 — ${wM(e,`native`)}`];let{bundle:i,source:a}=CM(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} — ${wM(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 — ${wM(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 EM=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)`},DM={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`:`${EM(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:lM([...new Set(i.flatMap(e=>TM(n,r,e)))])}};function OM({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||Rr(e.identity,t.value.through)):[]}function kM(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const AM={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`?kM(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return lM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=OM(e.value,n),u=lM([...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 ${Fr(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 ${Fr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Vr(o.charge.bytes,s)?[`the daemon holds ${Gr(o.charge)} of its ${Fr(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}}}},jM=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function MM(e,t){let n=Xj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Qj(e.terminal):{kind:`unknown`}}function NM({identified:e,tmuxClient:t},n){let r=Zj(e),i=MM(e,n),a=Xj(e)===null?jM:`${jM}, 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: ${$j}`];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 PM={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 lM(NM(t,n))}}},FM=e=>e.filter(e=>e.role===`statusline`),IM={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})=>zM(e,LM(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`:EM(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}}},LM=e=>{let t=FM(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, a placement with an effect of its own that is not drawn now, or a moving bar handed off to another lane, which comes back here when the handoff ends)`}: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 zM(e,t){let n=eM(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 rM(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 BM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function VM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return Zj(e);case`bundling`:case`unread`:case`configured`:return[Bj(e.name),e.version].filter(e=>e!==null).join(` `)}}function HM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return Xj(e);case`bundling`:case`unread`:return Bj(e.name);case`configured`:{let t=Bj(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 UM(e){let t=HM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${BM(e.glyphs)}`}}const WM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=UM(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=VM(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 ${BM(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:Gj(i.version,e);if(t===!0)return{ok:!0};let n=Bj(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 ${BM(n)} — set a Nerd Font as its font`)}}}};function GM(e){return e.join(`, `)}function KM(e){return`or set missingData: "ignore" on ${GM(e)}`}function qM(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, ${KM(t)}`]:[`${GM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${KM(t)}`]}function JM(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)}: ${EM(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)}`]:[]}const YM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>lM([...qM(e.pullRequests),...JM(e.rateLimits,t)])};function XM({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 ${oM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const ZM=[yM,DM,AM,SM,PM,fM,pM,mM,IM,WM,YM,{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`:`${EM(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:lM(e.value.flatMap(XM))}],QM=ZM.filter(e=>e.takesMark);function $M(e){return ZM.map(t=>({check:t,verdict:t.probe(e)}))}function eN(e){return ZM.find(t=>t.name===e)}const tN=`${P}doctor.`;function nN(e){let t=`${tN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function rN({target:e}){return`configTarget=${e.source}`}function iN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?Xj(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 aN(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 oN(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}=CM(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const sN=e=>`${e>=0?`+`:``}${Fr(e)}`;function cN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${kM(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`:`${OM(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Kr(i.charge)}${i.charge.kind===`stand-in`?`(${sN(-i.charge.gap)})`:``}:${Fr(i.charge.bytes)}`}/${Fr(a)} postMortems=${s}`}function lN(e){return`data=pr:${(()=>{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`})()},rateLimits:${(()=>{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`)}`})()}`}function uN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>dN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${R(i)}`;let a=FM(r.flatMap(e=>e.bars));return`frames=${Pj.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${R(i)}`}function dN(e){let t=eM(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 fN(e){let t=tM(e,uM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${R(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function pN(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 mN(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=UM(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 hN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function gN(e){return e.flatMap(({check:e,verdict:t})=>{let n=nN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:My},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:hN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?My:jy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const _N={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function vN(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(_N).map(([t,n])=>[`${e}${t}`,n]))}}const yN=`armed`,bN=`disarmed`,xN=`.armed`,SN=e=>e.endsWith(xN);function CN(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function wN(e,t,n){let r=`${e}${xN}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${yN}")`,s=CN(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:yN},[a]:{set:r,to:bN},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:bN}},disarm:a}}const TN=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function EN(e){return typeof e==`string`&&TN.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 DN(e){let t=EN(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const ON=[`/compact`,`/model`],kN=`/clear`;function AN(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=wN(`${e}clear`,{arm:kN,confirm:`${kN} ✓ confirm`},[{action:n,when:`true`}]);return{template:ON.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Vb} }}`,actions:{...Object.fromEntries(ON.map(e=>[t(e),{slash:DN(e)}])),...r.actions,[n]:{slash:DN(kN)}},variables:r.variables,disarm:r.disarm}}const jN=Array.from({length:10},(e,t)=>(t+1)*1e5),MN=jN[0],NN=jN[jN.length-1];function PN(e){let t=ts(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=MN&&n<=NN?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${MN}–${NN} tokens)`,`parse`)}function FN(e,t){let n=Math.min(t??NN,NN),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:jN.filter(e=>e<r).at(-1)??0,higher:jN.find(e=>e>r&&e<=n)??0}}function IN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Vb} }}{{ 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:DN(`/autocompact auto`)},...Object.fromEntries(jN.map(t=>[`${e}${t}`,{slash:DN(`/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 }}`,RN=`${P}edit`,zN=`${P}toolbar`,BN=vN(P),VN=`${P}commands`,HN=AN(`${VN}.`),UN=`${P}autocompact`,WN=IN(`${UN}.`,LN),GN=e=>({kind:`segment`,name:e}),KN=`${P}tab`,qN=e=>`${KN}.${e}`,JN=e=>`${qN(e)}.toggle`,YN=e=>({variable:KN,key:KN,member:e}),XN=`${P}save`,ZN=`${P}preset.save`,QN=`${P}preset.delete`,$N=e=>`${P}${e}`,eP=e=>`${P}apply.${e}`,tP=e=>`${P}reset.${e}`,nP=`${P}themeDefault.save`,rP=`${P}themeDefault.differs`,iP=`${P}themeDefault.theme`,aP={when:`{{ .${rP} }}`,template:`{{ action "${nP}" (printf "⤓ default for %s" .${iP}) }} {{ swatch "${eP(`theme`)}" .${iP} }}`},oP=`${P}resetAll`,sP=`${Li}.toggle`,cP=`${P}undo`,lP=`${P}back`,uP=`${lP}.step`,dP=`${P}navigation.back`,fP=lP,pP={template:`{{ if gt .${dP} 0 }}{{ action "${lP}" "◁" }}{{ else }}{{ fg (${dA}) "◁" }}{{ end }}`},mP=`${P}redo`,hP=`${P}doctor`,gP=`${hP}.run`,_P=e=>`${hP}.fix.${e}`,vP=(e,t)=>`${hP}.mark.${e}.${t}`,yP=e=>`${hP}.${e}`,bP={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},xP=AS(`${P}pickers`),SP=e=>`${P}${e}`,CP=e=>`${SP(e)}.toggle`,wP=e=>YS(e)?AS(`${P}${e}Pickers`):xP,TP=e=>{let t=wP(JS[KS[e].beside]);return{variable:t,key:t,member:e}},EP={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${QN}" (printf "🚮 delete %s" .${jx.preset.effectiveVar}) }}`}},DP=(e,t)=>`${P}list.${e}.${t}`,OP=e=>`${P}resettable.${e}`,kP=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${OP(e.name)})`).join(` `)})`,AP=Ub.map(e=>[Hb[e].switch.setting,e]),jP={variables:{},actions:{},segments:{}},MP=Object.fromEntries(AP.map(([e,t])=>[e,Xk(`${P}help.${e}`,lA[t],[],jP)])),NP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],PP=e=>{let t=t=>`.${Jb(e,t)}`,n=NP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${jx[Hb[e].switch.setting].effectiveVar} ${JSON.stringify(Hb[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},FP=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${Bi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,IP=`${P}fps`,LP=`{{ if eq .${Kb(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${Kb(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,RP=Object.fromEntries(AP.map(([e,t])=>[e,PP(t)])),_te=e=>qS.filter(t=>KS[t].beside===e),zP=Object.keys(jx).map(e=>{let t=jx[e],n=JS[e];return{...t,name:e,place:n,control:HS({label:t.label,domain:nC(t.configKey)},t.sessionKey,t.effectiveVar,eP(e),wP(n)),beneath:t.previews.map(e=>EP[e]),help:[MP[e]].filter(e=>e!==void 0),submenus:_te(e)}}),vte=e=>zP.filter(t=>t.place===e),yte=e=>zP.filter(t=>XS(t.place,e)),BP=e=>t=>`(print ${Di(t)} (ternary ${Di(` •`)} "" ${kP(yte(e))}))`,bte=e=>vte(e).flatMap(e=>[wte(e),...e.help,...e.submenus.map(e=>Si(SP(e),TP(e),$P(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(zP.flatMap(e=>[e.sessionKey,e.configKey]));const VP=wN(oP,{arm:`⟲`,confirm:`⟲ reset all?`},zP.map(e=>({action:tP(e.name),when:e.shown}))),xte=[`unsaved`,`history.undo`,`history.redo`],HP=e=>`${P}${e}`,UP=HP(`unsaved`),WP=(e,t)=>({body:t,shown:`(gt .${HP(e)} 0)`}),GP=[WP(`unsaved`,`{{ action "${XN}" (printf "💾 save %d" .${UP}) }}`),WP(`history.undo`,`{{ action "${cP}" "↶" }}`),WP(`history.redo`,`{{ action "${mP}" "↷" }}`),{body:VP.template,shown:`(or ${kP(zP)} ${VP.armed})`}],Ste={when:`{{ or ${GP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+GP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},KP=[{step:VP,place:`door`},{step:HN,place:`session`}],qP=e=>e.map(e=>e.step.disarm),JP=qP(KP),Cte=qP(KP.filter(e=>e.place!==`door`));function wte(e){let t=$N(e.name);return e.control.kind===`inline`?GN(t):Si(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>GN(DP(e.name,n)))},`drop`)}function YP(e){return e===Li}function XP(e){let t=GN(Li);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[XP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function Tte(e){return ZP(e)>0?e:XP(e)}function ZP(e){let t=0;for(let n of Uy(e))n.kind===`segment`&&YP(n.name)&&(t+=1);return t}function QP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&YP(e.name)||e.opens!==void 0&&QP(e.opens.body,!0):e.children.some(e=>QP(e,n))}const Ete={door:{direction:`horizontal`,content:[GN(fP)],after:[GN(RN),GN(XN)]},session:{direction:`vertical`,content:[GN(zN),{kind:`container`,direction:`horizontal`,children:[GN(VN),GN(UN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[GN(ZN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[GN(hP),...ZM.map(e=>GN(yP(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[GN(nP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function $P(e){let{direction:t,content:n,after:r}=Ete[e];return{kind:`container`,direction:t,children:[...n,...bte(e),...r]}}function eF(e){return e.kind===`segment`?YP(e.name)?{kind:`container`,direction:`horizontal`,children:[Si(e.name,zi,Ote,`above`),GN(IP)]}:e:kte(e)}function Dte(){return{kind:`container`,direction:`vertical`,children:[$P(`door`),{kind:`container`,direction:`horizontal`,children:WS.map(({member:e})=>Si(qN(e),YN(e),$P(e),`drop`))}]}}const Ote=Dte();function kte(e){return{...e,children:e.children.map(e=>eF(e))}}function Ate(e){let t={variables:{[Li]:Oi(Li,gi),[Bi]:{kind:`state`,key:Bi,default:`0`}},actions:{[sP]:ki(Li,Ri),[Bi]:{set:Bi,int:!0},[Li]:{do:[sP,...JP]},[gP]:{doctor:`run`},...BN.actions,...HN.actions,...WN.actions,[XN]:{save:!0},[cP]:{undo:!0},[uP]:{back:!0},[lP]:{do:[uP,...JP]},[mP]:{redo:!0},[ZN]:{preset:`save`},[nP]:{themeDefault:`save`},[QN]:{preset:`delete`,name:`{{ .${jx.preset.effectiveVar} }}`}},segments:{[Li]:{template:`{{ $door := ${Ei(Li,Di(e),Di(`✖`))} }}{{ if ${wi(zi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+FP},[IP]:{template:LP},[zN]:{template:BN.template},[VN]:{template:HN.template,when:HN.when},[UN]:{template:WN.template,bg:WN.bg,when:WN.when},[fP]:pP,[XN]:Ste,[nP]:aP,[ZN]:{template:`{{ action "${ZN}" "+ preset" }}`},[hP]:{template:`{{ action "${gP}" "🩺 doctor" }}`},[RN]:{template:`{{ action "${Bk}" "✎ arrange" "✎ done" }}`}}};t.variables[rP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[iP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[dP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of xte)t.variables[HP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[KN]=Oi(KN,gi);for(let{member:e,label:n}of WS){t.actions[JN(e)]=ki(KN,e),t.actions[qN(e)]={do:[JN(e),...Cte]};let r=BP(e);t.segments[qN(e)]={template:`{{ ${Ei(qN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,HN.variables,VP.variables),Mte(t),jte(t),t}function jte(e){for(let t of ZM){let n=nN(t.name),r=_P(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?aM:[];for(let n of i)e.actions[vP(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${vP(t.name,e)}" "${bP[e]}" }}`).join(``);e.segments[yP(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} "${jy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function Mte(e){for(let t of zP){Object.assign(e.actions,t.control.actions);let n=tP(t.name);e.actions[n]={reset:t.configKey},e.variables[OP(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${OP(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[$N(t.name)]={template:`${t.control.template}${RP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[DP(t.name,r)]=n})}Object.assign(e.actions,VP.actions),Object.assign(e.variables,jP.variables),Object.assign(e.actions,jP.actions),Object.assign(e.segments,jP.segments);for(let t of qS){let n=TP(t);e.actions[CP(t)]=ki(n.key,n.member),e.segments[SP(t)]={template:`{{ action "${CP(t)}" ${BP(t)(KS[t].trigger)} }}`}}}function Nte(e){let{variables:t,actions:n}=Yk();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Pte(e){let t=Ate(e.globals.menuGlyph??`🍫`);Nte(t);let n={...e.presets};for(let t of mS(e.presets)){let{node:r}=_S(e,t),i=eF(Tte(r));n[t]={...gS(e.presets,t),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const tF=`${Pi}live`,Fte=[`☐ live`,`☑ live`],nF=`${Pi}done`,rF=`${Pi}cancel`,iF=`${Pi}rewind`,aF=`${Pi}changes`,oF=`(gt .${aF} 0)`,Ite=`(or ${oF} (gt .${UP} 0))`,sF={variable:tF,key:tF,member:_i};function cF(e){return`${Pi}configuring.p${e}`}function lF(e){return`and ${wi(Wk)} (not ${wi(sF)}) (ne .${cF(e)} "true")`}function Lte(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${zk} "${xi(e)}")`).join(` `)} false }}`}}function uF(e,t,n){return`{{ if ${lF(e)} }}${t}{{ else }}${n}{{ end }}`}const Rte=`{{ and ${wi(Wk)} .preset.customized }}`,dF=Ii;function fF(e){return new Map([...Jee(e),...zte(e)])}const pF=`${Pi}addable`;function zte(e){return new Map([[pF,{members:Object.keys(e.segments).filter(e=>!dF(e)),library:{groups:RC.map(e=>({id:e,label:zC[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function mF(e,t,n){return n.segments[e]={template:t,when:Gk,bg:Qk},{kind:`segment`,name:e}}function Bte(e,t,n){let r=`${Pi}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Ov}`}) (action "${r}" "✖") }}`}function hF(e){return`{{ if ${wi(Wk)} }}${e}{{ end }}`}function gF(e,t){return e.reduce((e,t)=>`{{ if and ${wi(Wk)} ${wi(t)} }}true{{ else }}${e}{{ end }}`,t)}function Vte(e){return e.flatMap(e=>[...Uy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function Hte(e,t,n){return`${Hk}${e}.${t}.${n}`}function Ute(e,t,n,r){let i=zy(n),a=`${Pi}${e.presetIdent}`,o=Uk(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=AS(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:gi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:zk,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=Hte(e.presetIdent,i,r),l=`${Hk}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:lb(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=HS(BS(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 Si(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${iA}" }}`,ref:{variable:zk,key:zk,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const _F=`${Pi}label:`;function vF(e){if(e.startsWith(_F)){let t=e.slice(_F.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Wte(e,t,n,r){let i=zy(e),a=yF(n,i,e,t,i),o=Object.fromEntries(ib.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Si(a,r.ref,r.body,`drop`,gF([r.ref],`{{ ${lF(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(ib.map(e=>[e,r.drafts[e]]))}}function yF(e,t,n,r,i){let a=`${_F}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${xi(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function Gte(e,t,n,r){let i=zy(e),a=n?[bF(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=bF(r,o,i,`after`),c=Bte(r,o,i),l=r.segments[e.name],u=Ute(r,o,e,ab(l)),d=hF(c),f=hF(u.term);return[...a.map(e=>mF(e.host,e.template,r.artifacts)),{...Wte(e,l,r,u),lead:d,trail:f},{...t,when:uF(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},mF(s.host,s.template,r.artifacts)]}function Kte(e){return E.join(E.basename(E.dirname(e)),E.basename(e))}function qte(e,t,n,r){let i=r.segments[e.name],a=zy(e);return[{kind:`segment`,name:yF(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${Kte(t.file)} ${t.entry}`),when:`{{ ${lF(r.presetIdent)} }}`},{...n,when:uF(r.presetIdent,`false`,e.when??`true`)}]}function bF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Pi}${i}.insert.${t}`,s=`${Pi}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:pF,anchor:n,relation:r};let c=OS(o),l=kS(s,o,void 0),u=MS(l),d=jS(l,c);return a.variables[l]={...Oi(l,gi),within:[Wk]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ki(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${wi({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Ov}`}) $m }}{{ end }}`}}function xF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!dF(e.name)&&e.insertedBy===void 0),i=e=>xF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Hy(o,i);if(dF(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?Gte(o,s,a===r,t):qte(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:gF(Vte(n),uF(t.presetIdent,`true`,e.when))}}}function Jte(e,t,n,r,i,a,o){let s=`${Pi}${t}.resetLayout`,c=`${Pi}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Rte},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},SF(e,o)]}}function SF(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),SF(n,t)]}:{...e,children:[...e.children,t]}}function Yte(e,t,n,r,i,a){let{node:o}=_S(e,t),s={presetIdent:DS(t),rootKey:jC(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=xF(o,s);return n.variables[cF(s.presetIdent)]=Lte(s.configured),Jte(c,s.presetIdent,s.rootKey,n,r,i,a)}function Xte(e){let t={variables:{},actions:{},segments:{}},n=Xk(`${Pi}help`,cA,[Wk],t);t.variables[tF]=Oi(tF,gi),t.actions[tF]=ki(tF,sF.member),t.segments[tF]={template:Ti(tF,...Fte),when:Gk};let r={kind:`segment`,name:tF},i=n;t.variables[aF]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[nF]={do:[XN,Bk]},t.segments[nF]={template:`{{ if ${Ite} }}{{ action "${nF}" "✓ save" }}{{ else }}{{ action "${nF}" "✓ done" }}{{ end }}`,when:Gk},t.actions[iF]={rewind:!0},t.actions[rF]={do:[iF,Bk]},t.segments[rF]={template:`{{ action "${rF}" "↩ cancel" }}`,when:`{{ and ${wi(Wk)} ${oF} }}`};let a=[{kind:`segment`,name:nF},{kind:`segment`,name:rF}],o={...e.presets};for(let n of mS(e.presets)){let s=Yte(e,n,t,a,r,i);o[n]={...gS(e.presets,n),root:s}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function CF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Zte(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 Qte(e,t,n){let r=Vy(e,new Set(n.map(By).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const wF=/^-?\d+$/;function $te(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 ene(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 tne(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 nne(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 rne(e){return e===`config`?`set-config`:`set-state`}function ine(e,t,n){return t.kind===`int`?ene(`menu page "${e}"`):t.kind===`range`?tne(t.min,t.max,`${n} stepper "${e}"`):$te(t.allowed,`${n} "${e}"`,rne(n))}function TF(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:nne(e,n,t)}))}function EF(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 TF(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,ine(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 DF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};EF(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=EF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function ane(){return DF({},`config`,lne)}function one(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:TS(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:[CF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[CF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:TS(e.insertSegmentFrom,t).members.map(t=>CF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function sne(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?FC(n.persist):null;e?.scope===`preset-root`&&t.add(jC(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function cne(e){let t=fF(e);return[...sne(e),...Object.values(e.actions).flatMap(e=>one(e,t))]}function lne(e){return TF(cne(e),`config`)}const OF=ty(),une=new Set(OF),dne=new Set(Cy),kF=e=>e?une.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${OF.join(`, `)})`}:{ok:!1,reason:`theme name is required`},AF=e=>e?dne.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Cy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},jF=new Set([`1`,`true`]),MF=new Set([`0`,`false`]),NF={endcaps:AF,theme:kF,"toolbar-expanded":e=>jF.has(e)?{ok:!0,value:`1`}:MF.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function PF(){return DF(NF,`state`,RF)}function FF(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:TS(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 IF(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(NF,e.key))}function LF(e){let t=fF(e);return IF(Object.values(e.actions).flatMap(e=>FF(e,t)))}function RF(e){return TF(LF(e))}function zF(e){let t=PF(),n=ane();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const BF=`update.dismissed`,VF=`updateNotice`,HF=jx.updateNotice.sessionKey;function UF(){return zF({config:[{key:VF,allowed:[`false`]}],state:[{key:HF,allowed:[`false`]},{key:BF,allowed:[]}]})}function WF(e){try{return s.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const GF=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function KF(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*qF(e){let t=[];JF(e,(e,n)=>(t.push([n,e]),e)),yield*t}function JF(e,t){if(`copy`in e)return{...e,copy:t(e.copy,`copy`)};if(`open`in e)return{...e,open:t(e.open,`open`)};if(`preset`in e&&e.preset===`delete`)return{...e,name:t(e.name,`name`)};if(`run`in e){let n=e.run.map((e,n)=>t(e,`run.${n}`));return{...e,run:n,env:Object.fromEntries(Object.entries(e.env).map(([e,n])=>[e,t(n,`env.${e}`)]))}}return e}function YF(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function XF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{},...Dk},segments:$F(t.segments,ZF(t.segments,e.segments??{})),root:aS(e.root??Qx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:$F(t.presets,QF(t.presets,e.presets??{})),themeDefaults:$F(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function ZF(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function QF(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 $F(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const eI=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`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function tI(e){let t=eI.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)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function nI(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(nI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(nI)}default:return!1}}function rI(e){if(Array.isArray(e))return Object.freeze(e.map(rI));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]=rI(r);return Object.freeze(t)}return e}function iI(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 aI(e){return typeof e==`string`?e:String(e)}function oI(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 sI(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 cI=class extends Error{constructor(e,t){super(t),this.variable=e}};function lI(e){return e instanceof cI?e:e instanceof Error&&e.cause!==void 0?lI(e.cause):void 0}function uI(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: ${Yy.join(`, `)})`,line:q(e.source,t.split(`.`))}),null):pI(e,`${t}.cache`,n.cache)}function dI(e){return{required:!0,json:mI(),parse:(t,n,r,i)=>uI(t,n,i,e)??void 0}}const fI={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&gI(n)?{ttl:n}:Tb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${J(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Tb(e,t,`cache.watch_file must be a path string, got ${J(n)}`);let r=Mb(`cache.watch_file`,n);return r===null?{watch_file:n}:Tb(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}:Tb(e,t,`cache.depends_on must be an array of variable-name strings, got ${J(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Tb(e,t,`cache.key must be a non-empty template string, got ${J(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Tb(e,t,`cache.never must be the literal boolean true, got ${J(n)}`)}}};function pI(e,t,n){return Eb(e,fI,t,n)}function mI(){return zb(fI)}const hI=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function gI(e){return hI.test(e)}const _I=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 vI(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 yI(e){let t=_I.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${vI(t)}`}function bI(e){let t=_I.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${vI(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const xI=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),SI=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function CI(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function wI(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?SI.get(e.field):void 0;if(n===void 0){let e=[...SI.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${CI(n.declare)} under a name of your own`}function TI(e,t,n){if(n===void 0)return{};if(!yb(n))return e.issues.push({path:t,message:`${t} must be an object, got ${bb(n)}`,line:q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Bee(e,JI,`${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 ${bb(i)}`,line:q(e.source,t.split(`.`))});return}return i}}}function DI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Ree(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const OI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Tb(e,t,`parse.text must be the literal boolean true, got ${J(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?kI(e,t,n):Tb(e,t,`parse.regex must be a pattern string, got ${J(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Tb(e,t,`parse.json must be the literal boolean true, got ${J(n)}`)}}};function kI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Tb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Tb(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:zb(OI),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:q(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Eb(e,OI,`${t}.parse`,r.parse)??void 0)}}function jI(){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)=>yb(r.parse)&&`json`in r.parse?MI(e,t,r.default):gb(e,t,r,`default`)}}function MI(e,t,n){if(n!==void 0)return NI(n)?n:Tb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${J(n)}`)??void 0}function NI(e){return e!==null&&nI(e)}const PI={value:EI(),default:Ob()};function FI(){let e=jb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:xI.get(a);return o===void 0?a:Tb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const II={path:FI(),type:Pb([`string`,`number`,`boolean`]),default:DI()},LI={name:jb(),default:Ob()},RI={path:Nb(),readMode:Pb([`whole`,`first-line`]),parse:AI(),cache:dI(`file`),default:jI()},zI={command:jb(),parse:AI(),cache:dI(`shell`),default:jI()};function BI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const VI={template:jb(),type:Pb([`string`,`number`,`boolean`]),default:DI()},HI=BI(`a template variable recomputes whenever a variable it reads changes`),UI={layout:jb(),default:Ob()},WI=BI(`a time variable reads the instant its render is drawn at`),GI={key:jb(),default:Ob()},KI=`kind`;function qI(e,t,n={}){return{...Vee(KI,e,t),parse:(r,i,a)=>{Sb(r,n,i,a);let o=Cb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const JI={tag:KI,noun:`source kind`,memberNoun:`variable`,arms:{literal:qI(`literal`,PI),input:qI(`input`,II),env:qI(`env`,LI),file:qI(`file`,RI),shell:qI(`shell`,zI),template:qI(`template`,VI,HI),time:qI(`time`,UI,WI),state:qI(`state`,GI)},retired:{git:wI}};function YI(){return Rb(JI)}function XI(){return{type:`object`,additionalProperties:YI()}}const ZI=/^[A-Za-z_][A-Za-z0-9_]*$/,QI={pattern:ZI.source},$I={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},eL={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`,...QI}}}]},default:$I}},tL=[`label`,`domain`,`default`],nL=[`min`,`max`,`step`,`atLeast`];function rL(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function iL(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 rL(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 rL(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?rL(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(yb(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!nL.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}}:rL(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 rL(e,t,`domain must be "bool", a list of words, or { min, max }, got ${J(n)}`)}function aL(e,t,n){if(!yb(n))return rL(e,t,`${t} must be { label, domain, default }, got ${bb(n)}`);for(let r of Object.keys(n))tL.includes(r)||rL(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${tL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||rL(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${J(r)}`);let a=iL(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!oL(n.default)||!cb(o,n.default)?rL(e,`${t}.default`,`default must be ${db(o)}, got ${J(n.default)}`):o}function oL(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const sL={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${nb}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function cL(e){return ib.includes(e)}function lL(){return{required:!1,json:{type:`object`,propertyNames:{...QI,not:{enum:[...ib]}},additionalProperties:eL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!yb(i))return rL(e,a,`${a} must be an object of name → { label, domain, default }, got ${bb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!ZI.test(t)){rL(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(cL(t)){rL(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${sL[t]}`);continue}let r=aL(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const uL=Fi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function dL(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${uL})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!Ii(i)?i:rL(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Fi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${J(i)}`)}}}function fL(){return{required:!1,json:{type:`object`,propertyNames:QI,additionalProperties:$I},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!yb(i))return rL(e,a,`a placement's "settings" must be an object of setting name → value, got ${bb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))oL(n)?o[t]=n:rL(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${bb(n)}`);return o}}}function pL(e){return new Set(Object.keys(e.segments).filter(e=>!Ii(e)))}function mL(e,t,n){if(t===void 0)return{};if(!yb(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${bb(t)}`,line:q(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=xb(e,n.has(i)?wL:CL,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function hL(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${bb(s)}`,line:q(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${bb(i)}`,line:q(e.source,[...t.split(`.`),n])})}const gL={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function _L(){return{required:!0,json:gL,parse:(e,t,n,r)=>r[n]===void 0?Tb(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${tI(t.slice(9))}`)??void 0:hL(e,t,n,r)}}function vL(){return{required:!1,json:gL,parse:(e,t,n,r)=>r[n]===void 0?void 0:hL(e,t,n,r)}}function yL(){return{required:!1,json:{type:`object`,additionalProperties:gL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!yb(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${bb(i)}`,line:q(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=hL(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function bL(){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 ${J(i)}`,line:q(e.source,[...t.split(`.`),n])})}}}}function xL(){return{required:!1,json:XI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return TI(e,`${t}.${n}`,i)}}}const SL={template:_L(),description:Ob(),group:Pb(LC),width:bL(),justify:Pb(Oee),truncate:Pb(kee),bg:Ob(),fg:Ob(),when:Ob(),palette:Wee(),vars:xL(),settings:lL(),missingData:Pb($y),partials:yL()},CL={noun:`segment key`,fields:SL},wL={noun:`segment key`,fields:{...SL,template:vL()}};function TL(e,t){if(t===void 0)return{};if(!yb(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${bb(t)}`,line:q(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 ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function EL(e,t,n){if(t===void 0)return{};if(!yb(t))return Y(e,`actions`,`actions must be an object, got ${bb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=DL(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Y(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function DL(e,t,n,r){if(!yb(n))return Y(e,t,`${t} must be an action object, got ${bb(n)}`),null;if(`persistWhen`in n)return Y(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 i=GF.filter(e=>e in n);return i.length===1?kL(r)[i[0]](e,t,n):(Y(e,t,`action must declare exactly one of: ${GF.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function OL(e){return e===`<default>`?{dir:null}:E.isAbsolute(e)?{dir:E.dirname(e)}:{text:e}}const kL=e=>({set:(e,t,n)=>dR(e,t,n,`set`,sR),persist:(e,t,n)=>dR(e,t,n,`persist`,cR),copy:AL(`copy`),open:AL(`open`),reset:jL,undo:NL(`undo`),redo:NL(`redo`),back:NL(`back`),rewind:NL(`rewind`),save:NL(`save`),preset:PL,themeDefault:FL,doctor:LL,slash:RL,run:VL(e),do:HL});function AL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Y(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=hb(t,n,r,e);return i===null?null:{[e]:i}}}function jL(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=UL(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 ML={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 NL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Y(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Y(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${ML[e]}), got ${J(r[e])}`),null)}}function PL(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Y(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Y(e,`${t}.preset`,`preset must be "save" or "delete", got ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=hb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function FL(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Y(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${J(n.themeDefault)}`),null)}const IL={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function LL(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(IL,r),a=i?IL[r]:[...new Set(Object.values(IL).flat())];for(let r of Object.keys(n))a.includes(r)||Y(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Y(e,`${t}.doctor`,`doctor must be ${Object.keys(IL).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?QM:ZM;if(typeof o!=`string`||!s.some(e=>e.name===o))return Y(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return aM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Y(e,`${t}.mark`,`doctor mark must be ${aM.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function RL(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Y(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=EN(n.slash);return r.kind===`refused`?(Y(e,`${t}.slash`,r.reason),null):{slash:r.line}}const zL=[`run`,`env`,`refreshes`],BL=/^[A-Za-z_][A-Za-z0-9_]*$/;function VL(e){return(t,n,r)=>{for(let e of Object.keys(r))zL.includes(e)||Y(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${zL.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Y(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${J(a)}`);let o=r.env??{};(!yb(o)||Object.entries(o).some(([e,t])=>!BL.test(e)||typeof t!=`string`))&&Y(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${J(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Y(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${J(s)}`),`dir`in e||Y(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}BL.source;function HL(e,t,n){for(let r of Object.keys(n))r!==`do`&&Y(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===``)?(Y(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 ${J(r)}`),null):{do:r}}function UL(e,t,n,r,i,a){let o=hb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Y(e,s,i),null):o.includes(`/`)?(Y(e,s,a(o)),null):o}const WL={set:`the SessionState key to write`,persist:`the config globals field to write`};function GL(e,t,n,r){let i=WL[r],a=UL(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 KL(e){return e===`set`?`set-state`:`set-config`}const qL={to:fR(`set`)},JL={to:fR(`persist`)},YL={from:pR(`set`)},XL={from:pR(`persist`)},ZL={min:vR(),max:vR(),by:vR()},QL={int:hR()},$L={cycle:mR(`set`)},eR={cycle:mR(`persist`)},tR={removeSegment:gR(`removeSegment`)},nR={insertSegment:gR(`insertSegment`),anchor:gR(`anchor`),relation:_R()},rR={insertSegmentFrom:pR(`persist`),anchor:gR(`anchor`),relation:_R()},iR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},aR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function oR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Cb(e,t,n,r),c=Fb(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?Hee(s,...n):s}}const sR=[oR(`set`,qL),oR(`set`,YL),oR(`set`,ZL,[iR,aR]),oR(`set`,QL),oR(`set`,$L)],cR=[oR(`persist`,JL),oR(`persist`,XL),oR(`persist`,ZL,[iR,aR]),oR(`persist`,eR),oR(`persist`,tR),oR(`persist`,nR,[],[`insertSegment`]),oR(`persist`,rR,[],[`insertSegmentFrom`])];function lR(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 uR(e){let t=lR(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 dR(e,t,n,r,i){let a=GL(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Y(e,t,`${uR(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)||Y(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 fR(e){let t=KL(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>UL(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 pR(e){let t=KL(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===``){Y(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){Y(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===``)){Y(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){Y(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){Y(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Y(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${J(o)}`)}}}function mR(e){let t=KL(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`)){Y(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${bb(o)}`);return}let c=o;if(c.length<2){Y(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){Y(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Y(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){Y(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function hR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Y(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${J(r[n])}`);return}return!0}}}function gR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=hb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Y(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Y(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 _R(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Y(e,`${t}.${n}`,`relation must be "before" or "after", got ${J(i)}`);return}return i}}}function vR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Y(e,`${t}.${n}`,`${n} must be an integer, got ${J(i)}`);return}return i}}}const yR=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*bR(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2,i=[[0,r]];for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2,i.push([n.length,r]);continue}let t=r,a=e[r];if(r+=1,a===`"`||a===`'`||a==="`"){for(;r<e.length&&e[r]!==a;)r+=e[r]===`\\`&&a!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield{text:n,at:e=>{let[t,n]=i[0];for(let[r,a]of i)r<=e&&([t,n]=[r,a]);return n+e-t}},t=e.indexOf(`{{`,r+2)}}const xR=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,SR=RegExp(`^(?:(\\$)(?:\\.(${xR}))?|\\.(${xR})?)(?=[\\s)]|$)`);function CR(e,t,n){let r=SR.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 wR=/^(\w+)\b\s*([\s\S]*)$/;function*TR(e,t){let n=[t];for(let r of bR(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=wR.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,block:r};let i=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=i===null?s:CR(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(CR(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const ER=/(?<![.$])\btemplate\s+$/;function*DR(e,t,n){let r=0;for(let i of[...e.matchAll(yR)]){let a=i.index+i[0].length;ER.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:CR(e.slice(a),t,n),index:i.index}),r=a}}function*OR(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...TR(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...DR(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)}function kR(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const AR=new WeakMap;function jR(e,t){let n=AR.get(t);return n===void 0&&(n=kR(e=>[...OR(e,t)]),AR.set(t,n)),n(e)}const MR=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${xR})`,`g`);function*NR({code:e,dot:t,root:n}){let r=e.replace(yR,``);for(let e of[...r.matchAll(MR)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function PR(e,t){let n=new Map;for(let r of jR(e,t))for(let e of NR(r))n.has(e)||n.set(e,r.via);return n}const FR=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,IR={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*LR(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(yR)]){let a=e.slice(t,i.index),o=FR.exec(a);o===null?a.trim()!==``&&(n=0):(n=IR[o[1]],r=o[1]===`action`?`action`:`options`),n>0&&(yield{name:i[0].slice(1,-1),site:r,index:i.index},n--),t=i.index+i[0].length}}function RR(e,t){let n=new Map;for(let{code:r,via:i}of jR(e,t))for(let{name:e,site:t}of LR(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const zR=e=>Object.keys(IR).filter(t=>IR[t]>=e).join(`|`),BR=RegExp(`(?<![\\w.$])(?:(?:${zR(1)})\\s+|(?:${zR(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function VR(e,t){for(let{code:n}of jR(e,t))if(BR.test(n.replace(yR,`""`)))return!0;return!1}const HR=/(?<![\w.$])[A-Za-z_]\w*/g;function UR(e,t){let n=new Set;for(let{code:r}of jR(e,t))for(let[e]of r.replace(yR,``).matchAll(HR))n.add(e);return n}function WR(e,t){return new Set([...GR(e,t)].filter(e=>Object.hasOwn(t,e)))}function GR(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of jR(e,t))for(let{name:e}of DR(r,i,a))n.add(e);return n}const KR=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function qR(e,t,n){let r=KR(t),i=yk(t),a=[];for(let{dot:t,block:n}of TR(e,``)){let e=n.text.replace(yR,e=>` `.repeat(e.length));for(let i of e.matchAll(r))(i[1]===`$`?``:t)===``&&a.push(n.at(i.index+i[1].length+1));for(let{name:e,index:r}of[...DR(n.text,t,``),...LR(n.text)])i(e)&&a.push(n.at(r+1))}return[...new Set(a)].sort((e,t)=>t-e).reduce((e,r)=>e.slice(0,r)+n+e.slice(r+t.length),e)}function*JR(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*YR(e){for(let[t,n]of JR(e))yield[t,n]}function XR(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function ZR(e,t){return XR(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function QR(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),$R(r)&&n.add(e)};for(let[t,n]of YR(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function $R(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&Jy(e.parse)===`json`}function ez(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const tz=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),nz=`plugin.json5`,rz=/^[a-z][a-z0-9_]*$/;function iz(e,t){let n=E.basename(E.dirname(e));return rz.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function az(e){return`${e}.data`}function oz(e){return`${e}.json`}function sz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:cz(e)}}}function cz(e){return e instanceof fb?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 lz(e,t,n,r){return e.map(e=>iz(pA(E.dirname(t),e,r),n))}function uz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:vk(n),c=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(E.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${nz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${nz} and list that`;return c(t,o===void 0?e.config:fz(dz(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${E.basename(E.dirname(a))}" is not a plugin name (one matching ${rz}: it prefixes every name the plugin declares)`,e.config);let l=i.get(o);if(l!==void 0)return c(`plugin "${n.name}" is already listed, from ${l}`,e.config);i.set(o,a);let u=dz(e.config,o),d=sz(()=>{let i=s.readFileSync(a,`utf-8`),c=XF(vz(a,n,{source:i,json:Ia.default.parse(i)},t),u);return Nz(a,o,c),r(c,o,u!==e.config),c});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={...n,reason:d.reason};return c(d.reason,fz(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function dz(e,t){let n=yk(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,[t]:{kind:`dropped`,reason:ez(n),definition:n.path}}}}function pz(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>yk(t)(e))}function mz(e,t){let n=pz(e.config),r=[...e.rendering.keys()].map(yk),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=xk(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:ez(e)})):[{definition:a.definition,notice:a.notice}]}}function hz(e,t,n){let r=mS(e.presets).flatMap(t=>[...Uy(_S(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,gz(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=pz(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...Sz.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>RR(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...GR(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function gz(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,_z(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function _z(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,home:a}){let o=vk(t),c=[],l=()=>{throw new fb(e,c)};if(!yb(r))return c.push({path:``,message:`a plugin definition must be an object, got ${bb(r)}`}),l();for(let t of Object.keys(r))tz.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${E.basename(E.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...tz].join(`, `)}`});let u=r.data===void 0?void 0:Iz(r.data,e,i,a,c),d=r.sources===void 0?{}:Mz(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(ty()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:TI(f,`data`,{[az(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=TI(f,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(d)]])t.includes(`data`)&&c.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${az(o)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(d))Object.hasOwn(m,e)&&c.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let h={variables:{...p,...Tz(o,d),...Tz(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,Dz(o,t)])))},segments:Tz(o,Oz(o,mL(f,r.segments,new Set))),helpers:Tz(o,TL(f,r.helpers)),actions:Tz(o,kz(o,EL(f,r.actions,{dir:s.realpathSync(E.dirname(e))})))};c.push(...Cz(h,t));let g=yz(o,h);for(let[e,t]of wz(g))try{gk.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),g}function yz(e,t){let n=t=>qR(t,bk,e),r=t=>yk(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>bz(Zy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(Sz.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>bz(Zy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>xz(JF(e,n),r))}}function bz(e,t){return Xy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function xz(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const Sz=[`template`,`bg`,`fg`,`when`];function Cz(e,t){let n=e.helpers??{},r=_k.filter(e=>e!==t.scope).map(e=>({scope:e,ns:vk({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>yk(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${vk(t)}: a plugin names itself without its scope — write ${s}${bk}${n.slice(o.ns.length)}`})},o=[...[...wz(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of PR(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of RR(t,n))i===null&&a(e,r,!1);for(let n of GR(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))xz(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(Xy(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*wz(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of Qy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of Sz){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of Qy(r))yield[`segments.${t}.vars.${e}.${n}`,i]}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??{}))for(let[e,r]of qF(n))yield[`actions.${t}.${e}`,r]}function Tz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function Ez(e,t){return`${e}.${t}`}function Dz(e,t){return t.kind===`state`?{...t,key:Ez(e,t.key)}:t}function Oz(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,Dz(e,n)]))}]))}function kz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Ez(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>Ez(e,t))}:n]))}const Az=rz,jz={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function Mz(e,t,n){if(!yb(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${bb(e)}`}),{};let r=E.join(s.realpathSync(E.dirname(t)),`session`),i=JSON.stringify(jz),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!Az.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${Az}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=Fz(o,jz,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function Nz(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=Pz(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=yk(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new fb(e,a)}function Pz(e){return E.join(e.storage,oz(`<session id>`))}function Fz(e,t,n){return!yb(t)||!yb(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?Fz(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function Iz(e,t,n,r,i){if(typeof e==`string`&&e!==``)return pA(E.dirname(t),e,r);if(yb(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(E.isAbsolute(t)||t.startsWith(`~`)||E.normalize(t).split(E.sep)[0]===`..`){i.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){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return E.resolve(n.root,t)}if(yb(e)&&`project`in e){i.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}i.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 Lz(e,t){let n=[...[...e.dataDirs].reverse().map(e=>E.join(e,`cc-candybar`,`plugins`)),Rz(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:E.join(t,zz),scope:`repo`}]]}function Rz(e){return E.join(e.dataHome,`cc-candybar`,`plugins`)}const zz=E.join(`.cc-candybar`,`plugins`);function Bz(e,t){let n=Lz(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=Vz(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=iz(E.join(e,i,nz),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:E.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${nz}: move this file to ${E.join(e,`<name>`,nz)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function Vz(e){try{let t=s.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()||Hz(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 Hz(e,t){if(!t.isSymbolicLink())return!1;try{return s.statSync(E.join(e,t.name)).isDirectory()}catch{return!0}}function Uz(e){return s.existsSync(E.join(e,`.git`))}function Wz(e){let t=E.resolve(e);for(;;){if(Uz(t))return t;let e=E.dirname(t);if(e===t)return;t=e}}function Gz(e){let t=Wz(e);return t===void 0?{root:E.resolve(e),git:!1}:{root:t,git:!0}}function Kz(e){try{return F(e())}catch(e){return e.code===`ENOENT`?I:L(e.message,`read`)}}const qz=e=>Kz(()=>s.realpathSync.native(e)),Jz=(e,t)=>t.kind===`absent`?`${e} is not there`:t.reason;function Yz(e){let t=Kz(()=>s.readFileSync(E.join(e,`.git`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();return n===void 0?L(`${E.join(e,`.git`)} names no gitdir`,`parse`):F(E.resolve(e,n))}function Xz(e){let t=Kz(()=>s.readFileSync(E.join(e,`commondir`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.trim();return n===``?L(`${E.join(e,`commondir`)} is empty`,`parse`):F(E.resolve(e,n))}const Zz={kind:`unlinked`},Qz=e=>({kind:`unproven`,reason:e});function $z(e){let t=Wz(e);if(t===void 0)return Zz;let n=E.join(t,`.git`),r=Kz(()=>s.statSync(n));if(r.kind===`ok`&&r.value.isDirectory())return Zz;let i=Kz(()=>s.lstatSync(n));if(i.kind!==`ok`)return Qz(Jz(n,i));if(!i.value.isFile())return Qz(`${n} is not a file`);let a=Yz(t);if(a.kind!==`ok`)return Qz(Jz(n,a));let o=qz(a.value);if(o.kind!==`ok`)return Qz(Jz(a.value,o));let c=Xz(o.value);if(c.kind===`absent`)return Zz;if(c.kind===`failed`)return Qz(c.reason);let l=qz(c.value);if(l.kind!==`ok`)return Qz(Jz(c.value,l));if(E.dirname(o.value)!==E.join(l.value,`worktrees`))return Qz(`${o.value} is not a worktree of ${l.value}`);let u=E.join(o.value,`gitdir`),d=Kz(()=>s.readFileSync(u,`utf-8`));if(d.kind!==`ok`)return Qz(Jz(u,d));let f=E.resolve(o.value,d.value.trim()),p=qz(E.dirname(f));if(E.basename(f)!==`.git`||p.kind!==`ok`||p.value!==t)return Qz(`${o.value} is the worktree at ${f}, not ${t}`);let m=E.basename(l.value)===`.git`?E.dirname(l.value):l.value;return{kind:`linked`,main:E.join(m,E.relative(t,e))}}function eB(e){let t=qz(e),n=t.kind===`ok`?t.value:E.resolve(e),r=Wz(n);if(r===void 0)return{main:``,worktree:``,subpath:``,noRepo:!0};let i=E.relative(r,n),a=i===``?``:`/${i.split(E.sep).join(`/`)}`,o=$z(n);return o.kind===`linked`?{main:E.resolve(o.main,E.relative(n,r)),worktree:E.basename(r),subpath:a,noRepo:!1}:{main:r,worktree:``,subpath:a,noRepo:!1}}const tB=[`approved`,`declined`];function nB(e){return e.link.kind===`linked`?e.link.main:e.dir}const rB=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function iB(e,t){let n=nB(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=rB(e.value,n),i=rB(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function aB(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...iB(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&iB(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function oB(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function sB(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!tB.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${tB.join(` or `)}`};return{kind:`ok`,value:e}}function cB(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function lB(e){let t=cB(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const uB=[`json5`,`json`];function dB(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?uB.map(e=>E.join(t,`${fB}.${e}`)):[],...uB.map(e=>E.join(i,`${fB}.${e}`)),...uB.map(t=>`${pB(e)}.${t}`)])]}const fB=`.cc-candybar`;function pB(e){return E.join(e.configHome,`cc-candybar`,`config`)}function mB(e){return{path:e,scope:`plugins`}}function hB(e,t,n,r,i){let a=[],o=new Map;for(let t of dB(e,n,r,i)){let n=WF(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=s.realpathSync.native(E.dirname(t)),c=E.join(r,E.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||gB(e,t)?null:{dir:r,link:$z(r)}})}let c=[...o.values()],l=aB(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),_B(n)),u=c.filter(e=>e.repo===null||l.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(i===void 0)return{kind:`chain`,layers:u,home:vB(e,u),unchecked:a,repos:l};let[d]=a,f=i;return u.length>0?{kind:`chain`,layers:u,home:f,unchecked:a,repos:l}:d===void 0?{kind:`missing`,path:i,home:f,repos:l}:{kind:`unreadable`,...d,home:f,repos:l}}function gB(e,t){return uB.some(n=>t===`${pB(e)}.${n}`)}function _B(e){if(e===void 0||WF(e)!==`present`)return null;let t=Vz(E.join(e,zz)),n=s.realpathSync.native(e);return{dir:n,link:$z(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function vB(e,t){return t.find(t=>gB(e,t.path))?.path??`${pB(e)}.${uB[0]}`}function yB(e,t,n,r,i){let a=hB(e,t,n,r,i),o=a.kind===`chain`?a.layers:[];return{path:a.home,above:o.filter(e=>e.path!==a.home),repo:a.repos.plugins,cwd:r??null,locs:e}}function bB(e){return xB(e).join(`
|
|
180
|
+
`)||null}function xB(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 SB(e,t,n){let r=dB(e,t,n).filter(e=>WF(e)===`present`),i=new Map;for(let e of r){let t=E.dirname(e),n=E.basename(e).replace(/\.(json5|json)$/,``),r=E.join(t,n);i.has(r)||i.set(r,[]),i.get(r).push(e)}let a=[...i.values()].filter(e=>e.length>1);return a.length===0?null:`config-extension collision: ${a.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function CB(e,t,n,r){let i=E.join(e,t),a=()=>{let e;try{e=s.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&&Dn(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const wB={error:{rank:0,glyph:`⚠`,colors:FA},warning:{rank:1,glyph:`⚠`,colors:IA},info:{rank:2,glyph:`ℹ`,colors:LA}},TB={level:`error`,glyph:wB.error.glyph},EB={level:`warning`,glyph:wB.warning.glyph},DB={level:`info`,glyph:`⬆`},OB={level:`info`,glyph:`🔒`},kB={level:`info`,glyph:`🧪`},AB=e=>wB[e.level].colors;function jB(e,t){return{text:UA(e),link:t}}function MB(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=NB(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,TB)),...r,...i.flatMap(e=>o(e,EB))].sort((e,t)=>IB(e)-IB(t)),c=PB(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[jB(n.lines[0][0].text,FB(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function NB({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>jB(e,null)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:r,about:e,message:t,copy:n,lines:[i,...a]}]}function PB(e){return BB(e).map(e=>String(e*RB+1))}function FB(e,t,n,r){return Ta([{verb:ha,args:[e,t,n]}],`copy diagnostic ${r}`)}const IB=e=>wB[e.severity.level].rank;function LB(e){return e[0]?.severity.level??null}const RB=4096;function zB(e){let t=oe(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,9),16)%2**32}function BB(e){let t=new Map;return e.map(e=>{let n=zB(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function VB(e,t,n){return String(BB(e)[t]*RB+n+1)}function HB(e){let t=LB(e),n=e.length,{glyph:r,colors:i}=wB[t??`info`];return{label:t===null?``:`${r} ${n>9?`9+`:n}`,fg:i.fg,bg:i.bg,open:e.length===0?`0`:VB(e,0,0)}}function UB(e,t){let n=Number(e)-1,r=BB(t).indexOf(Math.floor(n/RB));return e===null||r===-1?null:{index:r+1,page:n%RB}}function WB(e,t){return Math.min(20,e??20,...t)}function GB(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=JB(i),c=ZB(o,s,[]),l=AB(o.severity),u=new U({bgcolor:l.bg,color:l.fg}),d=(e,t)=>YB(e,t===null?u:u.withLink(t)),f=(t,r)=>r===null?d(` `,null):d(t,qB(n,VB(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),p=(t,i)=>{let o=i>0?{index:a,page:i-1}:a>1?{index:a-1,page:0}:null,c=i<t-1?{index:a,page:i+1}:a<e.length?{index:a+1,page:0}:null,l=e.length>1||t>1,u=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return XB([d(`✕`,qB(n,`0`)),...l?[f(`‹`,o)]:[],d(u,null),...l?[f(`›`,c)]:[],d(`⧉ copy`,FB(n,r,VB(e,a-1,0),a))],s)},m=1;for(;;){let e=Math.max(1,i.rows-m),n=Math.min(RB,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=p(n,r);if(a.length>m){m=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,u=r===n-1&&l>0?[...o.slice(0,-1),...XB([d(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...u]}}function KB(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=HB(t),c=i===``?[]:[YB(i,new U({bgcolor:o,color:a}).withLink(qB(n,s)))];return ZB(e,JB(r),c)}function qB(e,t,n){return Ta([{verb:Wi,args:[e,Bi,t]}],n)}function JB(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const YB=(e,t)=>new K(`${e} `,{style:t,end:``,overflow:`ignore`}),XB=(e,t)=>Tj(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function ZB(e,t,n){let r=AB(e.severity),i=new U({bgcolor:r.bg,color:r.fg}),a=e=>e===null?i:i.withLink(e),o=tl(Math.max(2,t.width-1));return e.lines.flatMap((r,s)=>{let c=YB(s===0?e.severity.glyph:` `,i),l=r.flatMap(e=>e.text.split(` `).flatMap(e=>ol(e,o)).map(t=>YB(t,a(e.link)))),u=s===0?n:[];return XB([c,...l,...u],t)})}const QB=`repo-configs.json`;function $B(e){return E.join(e,`repo-configs`)}function eV(e){return E.join($B(e),QB)}const tV=e=>{let t=CB($B(e),QB,{},sB),n=CB(e,QB,{},sB),r=()=>s.existsSync(eV(e));return{read:()=>(r()?t:n).read(),update:e=>{if(r())return t.update(e);let i=n.read();return i.kind===`failed`?i:t.update(()=>e(i.value))}}};function nV(e,t,n){let r={superseded:[],absent:[],unchecked:[]},i=e.update(e=>{let i=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:WF(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&nB({dir:e,link:$z(e)})===t).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},oB(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function rV(e,t,n){return{sessionId:e,action:ma,declaration:t,evaluated:n}}function iV(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=tB.map(r=>jB(`[${r===`approved`?`approve`:`decline`}]`,Ta([{verb:ma,args:[t,e,r,n.sign(rV(t,e,r))]}]))),a=[jB(r,null),...i];return{severity:OB,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function aV(e){let t=E.basename(e),n=E.dirname(e);for(;;){let r=oV(n);if(r!==null)return{dir:r,name:t,leaf:n===E.dirname(e)};t=E.basename(n),n=E.dirname(n)}}function oV(e){try{return s.statSync(e).isDirectory()?s.realpathSync(e):null}catch{return null}}const sV=(e,t)=>k(t);function cV(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=An(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=aV(t);n&&=a;let o=r.has(e)?r.get(e):new Set;o?.add(i),r.set(e,o)}}for(let t of e.whole.map(oV))t!==null&&r.set(t,null);let i={dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},a=new Map(i.dirs.map(e=>{let t=Ac(e.path);return[e.path,Mc(t)?jc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function lV(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}function uV(e,t){if(t.kind===`failed`)return t;if(e.kind!==`changed`)return e;if(t.kind===`unknown`)return t;for(let n of t.paths)e.paths.add(n);return e}const dV=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([E.join(e,t)])},fV=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),pV=(e,t)=>e.kind===`listening`&&e.handle===t,mV=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var hV=class{slots=new Map;dirs=new Map;counters;logger;clock;closed=!1;constructor(e){this.clock=e.clock,this.counters=e.counters,this.logger=e.logger??sV}acquire(e,t,n){if(this.closed)return{release:()=>{},deaf:t.dirs.map(e=>({kind:`refused`,path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);for(let{dir:e}of r?.listeners??[])this.judged(e,`acquire`);let i=r??this.opened(e,t),a={onInvalidate:n};return i.holders.add(a),this.makeHandle(i,a)}follow(e,t,n){if(e!==null&&(e.key===t.key||t.unbound))return{watch:e,move:`kept`};let r={key:t.key,handle:this.acquire(t.key,t.targets,n)};return e?.handle.release(),{watch:r,move:`rebound`}}opened(e,t){let n={key:e,listeners:[],holders:new Set,debounce:null};for(let e of t.dirs){let t=this.dirFor(e),r={slot:n,dir:t,filter:e.filenames?new Set(e.filenames):null};t.listeners.add(r),n.listeners.push(r)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind===`listening`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=mV(e),n=this.dirs.get(t);if(n!==void 0)return this.judged(n,`acquire`),n;let r={path:e.path,recursive:e.recursive===!0},i={id:t,...r,listeners:new Set,state:this.open(r,()=>i,`acquire`,null)};return this.dirs.set(t,i),i}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}let n=Ac(e.path);Mc(n)&&jc(n)!==e.state.bound&&this.reopen(e,`another folder is at its path`)}judge(){for(let e of this.dirs.values())this.judged(e,`period`)}reopen(e,t){let n=e.state;n.kind===`listening`&&this.closeHandle(e.path,n.handle,t),e.state=this.open(e,()=>e,t,n),e.state.kind===`listening`?this.tell(e,{kind:`unknown`}):n.kind===`listening`&&this.tell(e,fV(e.state.deafness))}open(e,t,n,r){let i=e.path,a=jc(Ac(i));try{s.opendirSync(i).closeSync();let r=s.watch(i,{persistent:!1,recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.on(`error`,e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!pV(n.state,r))return;this.closeHandle(i,r,`error`);let a={kind:`failed`,path:i,reason:e.message};n.state={kind:`deaf`,deafness:a},this.tell(n,fV(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${R(i)} cause=${R(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t=e.message;return r?.kind===`deaf`&&r.deafness.kind===`refused`&&r.deafness.reason===t||this.logger(`warn`,`watch failed ${i}: ${t}`),{kind:`deaf`,deafness:{kind:`refused`,path:i,reason:t}}}}heard(e,t,n){let{state:r}=e;if(!pV(r,t))return;let i=n===E.basename(e.path)&&jc(Ac(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,dV(e.path,n));i&&this.judged(e,`moved`)}tell(e,t){for(let{slot:n}of e.listeners)this.fire(n,t)}fire(e,t){if(e.debounce!==null){e.debounce.window=uV(e.debounce.window,t);return}let n={window:t,cancel:this.clock.after(50,()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${R(e.key)}: ${t.message}`)}},{unref:!0})};e.debounce=n}makeHandle(e,t){return{get deaf(){return e.listeners.flatMap(({dir:e})=>e.state.kind===`deaf`?[e.state.deafness]:[])},release:()=>{!e.holders.delete(t)||e.holders.size>0||this.slots.get(e.key)===e&&(this.closeSlot(e,`last release`),this.slots.delete(e.key))}}}closeHandle(e,t,n){try{t.close()}catch{}this.counters&&this.counters.dirWatchesClosed++,this.logger(`info`,`dir watch closed path=${R(e)} cause=${R(n)}`)}closeSlot(e,t){e.debounce!==null&&(e.debounce.cancel(),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;e.listeners.delete(n),!(e.listeners.size>0)&&(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),this.dirs.delete(e.id))}this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}};const gV=`#/definitions/LayoutNode`,_V={kind:`container`,direction:`vertical`,children:[]};function vV(e){return{required:!0,json:{const:e},parse:()=>e}}function yV(){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 ${J(i)}`,line:q(e.source,[`root`])}),``)}}}function bV(){return{required:!0,json:{enum:[...Ly]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Ly.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Ly.join(`, `)} (got ${JSON.stringify(i)})`,line:q(e.source,[`root`])}),`vertical`)}}}function xV(e){return{required:!0,json:{type:`array`,items:{$ref:gV}},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 ${bb(a)}`,line:q(t.source,[`root`])}),[])}}}const SV={noun:`layout-node key`,fields:{kind:vV(`segment`),name:yV(),when:Ob(),id:dL(),settings:fL()}},CV=()=>Pb(uv),wV={noun:`layout-node key`,fields:{kind:vV(`container`),direction:bV(),children:xV(Db(()=>kV)),when:Ob(),distribution:CV()}};function TV(){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 ${J(i)}`,line:q(e.source,[...t.split(`.`),n])}),``)}}}const EV={noun:`layout-node key`,fields:{seg:TV(),when:Ob(),id:dL(),settings:fL()}},DV={noun:`layout-node key`,fields:{h:xV(Db(()=>kV)),when:Ob(),distribution:CV()}},OV={noun:`layout-node key`,fields:{v:xV(Db(()=>kV)),when:Ob(),distribution:CV()}},kV=(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:q(e.source,[`root`])}),_V):{kind:`segment`,name:n};if(!yb(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 ${bb(n)}`,line:q(e.source,[`root`])}),_V;if(n.kind===`container`)return xb(e,wV,t,n)??_V;if(n.kind===`segment`)return xb(e,SV,t,n)??_V;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
181
181
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
182
|
-
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),vV;if(n.kind===`group`){let r=Sb(e,zV,t,n);return r===null?vV:(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}),VV(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:q(e.source,[`root`])}),vV}if(a){let r=Sb(e,DV,t,n);return r===null?vV:{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=Sb(e,OV,t,n);return r===null?vV:{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=Sb(e,kV,t,n);return r===null?vV:{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:q(e.source,[`root`])}),vV};function jV(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Zx.source},additionalProperties:{$ref:_V}},parse:(e,t,n,r)=>{let i=r[n];if(!bb(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${xb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Zx.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:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=AV(e,`${t}.${n}.${r}`,o)}return a}}}const MV={noun:`root key`,fields:{rows:jV(),when:kb(),distribution:wV()}};function NV(e,t,n){return bb(n)&&`rows`in n?Sb(e,MV,t,n)??{rows:{}}:AV(e,t,n)}const PV={noun:`insert key`,fields:{seg:EV(),id:fL(),before:kb(),after:kb()}};function FV(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Sb(e,PV,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(Ii(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return Ii(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${xb(t)}`,line:q(e.source,[`insert`])}),[])}function IV(){return{required:!0,json:{type:`string`,pattern:Zx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Zx.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 "${gi}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function LV(){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 ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function RV(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=gb(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:q(e.source,[...t.split(`.`),n])});return}return i}}}}const zV={noun:`layout-node key`,fields:{kind:yV(`group`),name:IV(),label:RV(),open:Ab(),direction:Fb(Ry),key:LV(),bg:kb(),fg:kb(),when:kb(),distribution:wV(),children:SV(Ob(()=>AV))}};function BV(e){return e.key??`groups.`+e.name}function VV(e){let t=ji+e.name;return Si(t,{variable:t,key:BV(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function HV(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function UV(e,t){Nk(e,t,ji,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&HV(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}.`)&&BV(t)===BV(r)&&HV(e,t.path,`group "${t.name}" shares key "${BV(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=BV(t);if(i.has(n)||i.set(n,gi),t.open===!0){let r=i.get(n);r!==`closed`&&HV(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=ji+e.name,r=BV(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Oi(r,i.get(r)),o[t]=ki(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 WV=`menu`,GV=`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`,KV=e=>e.kind===`call`&&e.name===`dict`,qV=e=>e.kind===`literal`&&typeof e.value!=`object`,JV=e=>yi(``,e,2)===void 0;function YV(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&&KV(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(KV))return t(`whose options (dict …) is not its last argument — ${GV}`);if(i!==void 0&&a===void 0&&!qV(i)&&JV(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=yi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${GV}`);let c=a===void 0?{}:nD(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=LS(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Mk(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 "${jS(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 XV(e){let t=OT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===WV).map(YV)}catch{return`parse-failed`}}function ZV(e,t){let n=XV(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:AS(t,e.apply,e.options.key),member:kS(e.apply)}]:[])}function QV(e){let t=OT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(WV)}catch{return!1}}function $V(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function eH(e,t){Nk(e,t,Mi,`{{ menu }} helpers`),Nk(e,t,Ni,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))QV(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:q(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`&&QV(i)&&$V(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.`)}for(let[n,i]of Object.entries(r.partials??{}))QV(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of Wy(iS(t.root)))typeof n.when==`string`&&QV(n.when)&&$V(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||!QV(r))continue;let n=XV(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:tH(r.apply);n!==void 0&&$V(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function tH(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(kS(e)===`closed`)return`whose apply action is named "${gi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function nH(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 hS(e.presets)){let a=new Map,s=new Map;for(let c of Wy(vS(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,XV(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=By(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||tH(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=kS(i),f=AS(u,i,l.key),p=NS(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=MS(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]=ki(f,d),n[f]=Oi(f,gi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function rH(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const iH={noun:`style key`,fields:{hueShift:jb(),chromaScale:jb({min:0}),lightnessScale:jb(),lightnessShift:jb()}};function aH(e,t){if(!bb(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${xb(t)}`,line:q(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:q(e.source,[`styles`,r])});continue}if(Ey(r)){e.issues.push({path:`styles.${r}`,message:rH(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=Sb(e,iH,`styles.${r}`,i);t!==null&&(n[r]={...yu,...t})}return n}const oH={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:NV(e,`${t}.${n}`,r[n])},globals:{required:!1,json:bC(),parse:(e,t,n,r)=>r[n]===void 0?void 0:yC(e,`${t}.${n}`,r[n])}}};function sH(e,t){if(!bb(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${xb(t)}`,line:q(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:q(e.source,[`presets`,r])});continue}let t=Sb(e,oH,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function cH(e,t){let n=[...t].map(([e,t])=>[yk(e),t]);return t=>{if(YP(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=xk(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function lH(e){return e.kind===`plugin`||e.kind===`missing`}function uH(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>eS(e)?Object.values(e.rows):[e],o=[e.root,...Object.values(e.presets).flatMap(e=>e.root===void 0?[]:[e.root])];for(let e of o.flatMap(a))for(let t of Wy(e))t.kind===`segment`&&i(By(t),{seg:t.name});for(let e of t)i(e.id??e.seg,{seg:e.seg,anchor:e.anchor});let s=new Set,c=e=>n(e.seg).kind===`absent`||e.anchor!==void 0&&s.has(e.anchor);for(let e=!0;e;){e=!1;for(let[t,n]of r)!s.has(t)&&n.every(c)&&(s.add(t),e=!0)}return e=>s.has(e)}function dH(e){let t=0,n=cH(e.segments,new Map),r=e=>{let r=n(e).kind===`declared`;return r||(t+=1),r},i=e=>({...e,children:e.children.flatMap(e=>a(e))}),a=e=>e.kind===`container`?[i(e)]:r(e.name)?[Uy(e,i)]:[],o=e=>a(e)[0]??fH,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>eS(e)?s(e):o(e),l=e=>e.root===void 0?e:{...e,root:c(e.root)},u={...e,root:s(e.root),presets:Object.fromEntries(Object.entries(e.presets).map(([e,t])=>[e,l(t)]))};return t===0?e:u}const fH={kind:`container`,direction:`horizontal`,children:[]};var pH=Ee((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()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(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 Lt.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=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(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:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return _e(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(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 w(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:_e(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 T(e,t){return{t:e,i:t,o:ee,u:te}}function ee(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)||!Ye(e.h[t]))&&this.u(e,t,n,!1)===null?0:Ye(n.value)?1:(It(r,t,ne(e,0,0,n,!1,!1)),2)}function te(e,t,n,r){let i=ne(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function E(e,t,n){var r;let{name:i,addInitializer:a}=n;return Ye(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 ne(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Ye(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 D(e,t){return{t:e,i:t,o:re,u:ie}}function re(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ie(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function O(e,t,n){function r(e){let n=Pt({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=St(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&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 ae(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ce(e,t,n){function r(e,t){let n=St(e)[j];return(n.V??=new Map).set(o,()=>new _n(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[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function le(e){return{t:Jt,i:e,o:ue,u:de}}function ue(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=Ve(n.set)?n.set:_e(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(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?nn:sn;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 de(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:_e(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?nn:sn).u(e,t,n,r))}function fe(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function pe(e){return e||Xt}function me(e){return fe(e,ce)}function he(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 ge(e){return fe(e,O)}function _e(e,t,n=!1,r){function i(){return ve(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ve(e,t,n,r,i){let a=ye(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{be(a)}}function ye(e,t){let n=N.trackingDerivation,r=!t||!n;k();let i=N.allowStateChanges;r&&De();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function be(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Ne(),e.R&&Oe(e.k),N.suppressReactionErrors=!1}function xe(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 Se(e){return e instanceof xn}function Ce(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=De(),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 Oe(t),!0}if(e.K===2)return Oe(t),!0}}return ke(e),Oe(t),!1}}}function we(e,t,n){ke(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&&je(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Ae(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Te(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)je(t[n],e);e.K=-1}function Ee(e){let t=De();try{return e()}finally{Oe(t)}}function De(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Oe(e){N.trackingDerivation=e}function ke(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Ae(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function je(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Me(e))}function Me(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function k(){N.inBatch++}function Ne(){--N.inBatch===0&&(Ie(),!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 yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Pe(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Pe))}function Fe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Me(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 A(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 Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){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 Re(e){return fe(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?_e(t.name||`<unnamed action>`,t,e):r(n)?_e(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ve(0,!1,e,this,void 0)}function Ve(e){return r(e)&&!0===e.isMobxAction}function He(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ue(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 Ue(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function We(e,t,n,i){let a=typeof i==`function`?Tt(t,n):Tt(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 Ge(e,t,n,r){let i=Ut(t);return Ot(()=>{let t=St(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ke(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(Ke)),t}function qe(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),qe)),t}function Je(e){r(e.cancel)&&e.cancel()}function Ye(e){return!0===e?.isMobXFlow}function Xe(e,t){var n;if(t===void 0)return bn(e);if(!1===wt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Tt(e,t)):!1}function Ze(e,t){if(!e)return!1;if(t!==void 0){if(wt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return wt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function Qe(e){return Ze(e)}function $e(e){return wt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):yt(e)?e.map((e,t)=>t):void t(5)}function et(e,n){return wt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):yt(e)?n>=0&&n<e.length:void t(10)}function tt(e){if(wt(e))return e[j].it();t(38)}function nt(e,t,n){if(bn(e)){let r,i=!0;return He(()=>{let a=e.get();if(!i||n){let n=De();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Oe(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),ft(e,t)}function rt(e,t,n){return e.set(t,n),n}function it(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Qe(e))return e;if(vn(e)||bn(e))return it(e.get(),t);if(t.has(e))return t.get(e);if(yt(e)){let n=rt(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=it(e,t)}),n}if(sr(e)){let n=rt(t,e,new Set);return e.forEach(e=>{n.add(it(e,t))}),n}if(ir(e)){let n=rt(t,e,new Map);return e.forEach((e,r)=>{n.set(r,it(e,t))}),n}{let n=rt(t,e,{});return tt(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=it(e[r],t))}),n}}function at(e,t){k();try{return e.apply(t)}finally{Ne()}}function ot(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=_e(`When-effect`,t);var a=He(t=>{xe(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function st(e){return e[j]}function ct(e){return e.st!==void 0&&e.st.length>0}function lt(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 ut(e,n){let r=De();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{Oe(r)}}function dt(e){return e.ot!==void 0&&e.ot.length>0}function ft(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 pt(e,t){let n=De(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Oe(n)}}function mt(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!==Lt;){let t=Ft(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 ht(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function gt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function _t(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function vt(e){return function(){let t=this[j];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 yt(e){return a(e)&&er(e[j])}function bt(e){return e[Symbol.toStringTag]=`MapIterator`,Mt(e)}function xt(e){return e[Symbol.toStringTag]=`SetIterator`,Mt(e)}function St(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,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 M[r]??(M[r]=le({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Ct(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function wt(e){return!!a(e)&&dr(e[j])}function Tt(e,n){if(typeof e==`object`&&e){if(yt(e))return n!==void 0&&t(23),e[j].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,Dt(e)),r}if(wt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Dt(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Et(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Et(Tt(e,n))}function Dt(e,t){let n;if(t!==void 0)n=Tt(e,t);else{if(Ve(e))return e.name;n=wt(e)||ir(e)||sr(e)?Et(e):Tt(e)}return n.tt}function Ot(e){let t=De();k();try{return e()}finally{Ne(),Oe(t)}}function kt(e,t,n=-1){return At(e,t,n)}function At(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=jt(e),t=jt(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(!At(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)||!At(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function jt(e){return yt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Mt(e){return e[Symbol.iterator]=Nt,Pt(Object.create(pr),e)}function Nt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Pt=Object.assign,Ft=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=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 Fe(this)}reportChanged(){k(),A(this),Ne()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=le(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=ae(`observable`),Qt=ae(`observable.ref`,{A:y}),$t=ae(`observable.shallow`,{A:function(e,t,n){return e==null||wt(e)||yt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=ae(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=pe(t);return new _n(e,he(n),n.name,!0,n.equals)},array(e,t){let n=pe(t);return function(e,t,n=`ObservableArray`,r=!1){return Ot(()=>{let i=new Qn(n,t,r);It(i.j,j,{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,he(n),n.name)},map(e,t){let n=pe(t);return new rr(e,he(n),n.name)},set(e,t){let n=pe(t);return new or(e,he(n),n.name)},object:(e,t,n)=>Ot(()=>Ge(function(e,t){var n;return(n=(e=St(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=me(Qt),rn=me($t),an=me(Zt),on=me(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?ce(Zt,e,t):Qe(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=D(cn),un=ge(D(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return O(ln,e,t);if(o(e))return ge(D(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Pt(dn,ln);let pn=0,mn=1,hn=(fn=Ft(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){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(ct(this)){let t=ut(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(),dt(this)&&pt(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 vn=l(`ObservableValue`,_n);var yn=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=_e(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,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(Fe(this),Ce(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(Pe)}else Ce(this)&&(this.Nt(),k(),this.rt=this.Rt(!1),Ne());let e=this.rt;if(Se(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||Se(e)||Se(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=we(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||(Te(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`,yn);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),Ie())}X(){if(!this.isDisposed){k(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,Ce(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Ne()}}track(e){if(this.isDisposed)return;k(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=we(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Te(this),Se(n)&&this.Pt(n.cause),Ne()}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||(k(),Te(this),Ne()))}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[j]=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=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(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=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return E(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&&Je(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Je(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=fe(Wn,E),qn={has:(e,t)=>st(e).et(t),get:(e,t)=>st(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=st(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=st(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=st(e).l(t,n))==null||r},ownKeys:e=>st(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?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[j];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 Wt(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=Rt),ct(this)){let r=ut(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;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=dt(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&&pt(this,i)}Ft(e,t,n){let r=dt(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&&pt(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(ct(this)){let n=ut(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[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];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[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];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[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};ht(`at`,gt),ht(`concat`,gt),ht(`flat`,gt),ht(`includes`,gt),ht(`indexOf`,gt),ht(`join`,gt),ht(`lastIndexOf`,gt),ht(`slice`,gt),ht(`toString`,gt),ht(`toLocaleString`,gt),ht(`toSorted`,gt),ht(`toSpliced`,gt),ht(`with`,gt),ht(`every`,_t),ht(`filter`,_t),ht(`find`,_t),ht(`findIndex`,_t),ht(`findLast`,_t),ht(`findLastIndex`,_t),ht(`flatMap`,_t),ht(`forEach`,_t),ht(`map`,_t),ht(`some`,_t),ht(`toReversed`,_t),ht(`reduce`,vt),ht(`reduceRight`,vt);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[j]=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,Ot(()=>{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 _n(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(ct(this)){let r=ut(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(ct(this)&&!ut(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=dt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return at(()=>{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&&pt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}}Jt(e,t){at(()=>{var n;let r=new _n(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=dt(this);n&&pt(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 bt({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 bt({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)),at(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.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(){at(()=>{Ee(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return at(()=>{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[j]=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),Ot(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){at(()=>{Ee(()=>{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(ct(this)){let t=ut(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){at(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=dt(this);t&&pt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=dt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return at(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return xt({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 xt({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)?at(()=>{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=Yt){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 Wt(`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 yn)return n.set(t),!0;if(ct(this)){let n=ut(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=dt(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&&pt(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 _n(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{k();let r=this.Dt(e);if(!r)return r;if(ct(this)){let n=ut(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=Pt({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Ne()}return!0}S(e,t,n,r=!1){try{k();let i=this.Dt(e);if(!i)return i;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Ct(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 It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Ne()}return!0}m(e,t,n=!1){try{k();let r=this.Dt(e);if(!r)return r;if(ct(this)&&!ut(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=Ct(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 It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Ne()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;k();let r=dt(this),i=this.j.get(e),a;if(i||!r||(a=Ft(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 _n&&(a=i.rt),A(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&pt(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Ne()}return!0}Yt(e,t){var n;let r=dt(this);r&&r&&pt(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(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=xe,e._allowStateChangesInsideComputed=Be,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=be,e._getAdministration=Et,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||yt(e)||vn(e)?r=Et(e):wt(e)&&(r=Et(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=ye,e.action=In,e.actionBound=Rn,e.autorun=He,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return kt(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,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(wt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return wt(e)?$e(e).map(t=>[t,e[t]]):ir(e)?$e(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):yt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ge,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(et(e,n))return wt(e)?e[j].Tt(n):ir(e)?e.get(n):yt(e)?e[n]:void t(11)},e.getAtom=Tt,e.getDebugName=Dt,e.getDependencyTree=function(e,t){return Ke(Tt(e,t))},e.getObserverTree=function(e,t){return qe(Tt(e,t))},e.has=et,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return lt(Et(e,t),n)}(e,t,n):function(e,t){return lt(Et(e),t)}(e,t)},e.isAction=Ve,e.isBoxedObservable=vn,e.isComputed=function(e){return Xe(e)},e.isComputedProp=function(e,t){return Xe(e,t)},e.isFlow=Ye,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=Qe,e.isObservableArray=yt,e.isObservableMap=ir,e.isObservableObject=wt,e.isObservableProp=function(e,t){return Ze(e,t)},e.isObservableSet=sr,e.keys=$e,e.makeAutoObservable=function(e,t,n){return o(e)?Ge(e,e,t,n):(Ot(()=>{let r=St(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>mt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return Ot(()=>{let r=St(e,n)[j];Ht(t).forEach(e=>mt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return nt(Et(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Et(e);if(yt(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)&&!wt(e))return nt(r,t,n);return ft(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return We(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return We(`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=qt,e.ownKeys=tt,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=xe(!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=Ue(n),d,f=!0,p=!1,m=n.equals||Kt,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){wt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):yt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Be,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){k();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Ne()}return}wt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):yt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),k(),r>=n.length&&(n.length=r+1),n[r]=i,Ne()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return it(e,new Map)},e.transaction=at,e.untracked=Ee,e.values=function(e){return wt(e)?$e(e).map(t=>e[t]):ir(e)?$e(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):yt(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 Pt(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ot(e,n,Pt({},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):ot(e,t,n||{})}})),mH=Ee((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++M.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=E(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 x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function ee(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function te(e){return e===null?null:typeof e==`object`?``+e:e}function E(e,t){return o.hasOwnProperty.call(e,t)}let ne=Object.getOwnPropertyDescriptors;function D(e,t){return!!(e&t)}function re(e,t,n){return n?e|=t:e&=~t,e}function ie(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let O=Symbol(`mobx administration`);var ae=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 D(this.flags_,1)}set isBeingObserved(e){this.flags_=re(this.flags_,1,e)}get isPendingUnobservation(){return D(this.flags_,2)}set isPendingUnobservation(e){this.flags_=re(this.flags_,2,e)}get diffValue(){return+!!D(this.flags_,4)}set diffValue(e){this.flags_=re(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let oe=b(`Atom`,ae);function se(e,t=f,n=f){let r=new ae(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ce(e,t){return e===t}function le(e,t){return Li(e,t)}function ue(e,t){return Li(e,t,1)}let de=Object.is;function fe(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?ut.array(e,{name:n}):g(e)?ut.object(e,void 0,{name:n}):x(e)?ut.map(e,{name:n}):C(e)?ut.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function pe(e,t,r){if(e==null||Ai(e)||pi(e)||_i(e)||Si(e))return e;if(Array.isArray(e))return ut.array(e,{name:r,deep:!1});if(g(e))return ut.object(e,void 0,{name:r,deep:!1});if(x(e))return ut.map(e,{name:r,deep:!1});if(C(e))return ut.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function me(e){return e}function he(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ge=`override`,_e={annotationType_:ge,make_:ye,extend_:be};function ve(e){return e.annotationType_===ge}function ye(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),E(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function be(e,t,r,i){n(44,this.annotationType_)}function xe(e,t){return{annotationType_:e,options_:t,make_:Se,extend_:Ce}}function Se(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,Ee(e,this,t,n,!1)),2)}function Ce(e,t,n,r){let i=Ee(e,this,t,n);return e.defineProperty_(t,i,r)}function we(e,t,r){ie(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>bt(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 Te(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 Ee(e,t,n,r,i=M.safeDescriptors){var a,o;Te(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:bt(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 De(e,t){return{annotationType_:e,options_:t,make_:Oe,extend_:ke}}function Oe(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&&(!E(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Me(e,this,t,n,!1,!1)),2)}function ke(e,t,n,r){let i=Me(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Ae(e,t,n){var r;ie(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 je(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 Me(e,t,n,r,i,a=M.safeDescriptors){je(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 k(e,t){return{annotationType_:e,options_:t,make_:Ne,extend_:Pe}}function Ne(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Pe(e,t,n,i){return A(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Fe(e,t,n){ie(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 kt(o)}return o(function(){let e=Di(this)[O],n=this,r=e.values_.get(a);r instanceof kt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[O],n=e.values_.get(a);if(n instanceof kt&&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 A(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 Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??fe,r)}function ze(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ie(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[O];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??fe,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[O]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[O]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(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 Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.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?ot:ut;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 Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(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?ot:ut).extend_(e,t,n,r))}function qe(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 Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:me}),Qe=Ie(`observable.shallow`,{enhancer_:pe}),$e=Ie(`observable.struct`,{enhancer_:he});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?fe:e.deep===!1?me:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??fe:fe}function it(e,t,n){return t&&typeof t.kind==`string`?ze(Xe,e,t):xr(e)?e:g(e)?ut.object(e,t,n):Array.isArray(e)?ut.array(e,t):x(e)?ut.map(e,t):C(e)?ut.set(e,t):typeof e==`object`&&e?e:ut.box(e,t)}let at={box(e,t){let n=Ye(t);return new Dt(e,tt(n),n.name,!0,n.equals)},array(e,t){let n=Ye(t);return oi(e,tt(n),n.name)},map(e,t){let n=Ye(t);return new gi(e,tt(n),n.name)},set(e,t){let n=Ye(t);return new xi(e,tt(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Fe)}let pt=k(dt),mt=ft(k(`computed.struct`,{equals:le})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Fe(pt,e,t);if(g(e))return ft(k(dt,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 kt(r)};r(ht,pt);let gt=0,_t=1,vt=i(()=>{},`name`)?.configurable??!1,yt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function bt(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 xt(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),vt&&(yt.value=e,a(o,`name`,yt)),o}function xt(e,t,n,r,i){let a=St(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Ct(a)}}function St(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=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Tt(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:_t++,parentActionId_:gt};return gt=d.actionId_,d}function Ct(e){gt!==e.actionId_&&n(30),gt=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Et(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function wt(e,t){let n=Tt(e);try{return t()}finally{Et(n)}}function Tt(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Et(e){M.allowStateChanges=e}var Dt=class extends ae{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=de){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!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(Ft(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,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 te(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Ot=b(`ObservableValue`,Dt);var kt=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 jt(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_=bt(this.name_+`-setter`,e.set)),this.equals_=e.equals||de,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return D(this.flags_,1)}set isComputing(e){this.flags_=re(this.flags_,1,e)}get isRunningSetter(){return D(this.flags_,2)}set isRunningSetter(e){this.flags_=re(this.flags_,2,e)}get isBeingObserved(){return D(this.flags_,4)}set isBeingObserved(e){this.flags_=re(this.flags_,4,e)}get isPendingUnobservation(){return D(this.flags_,8)}set isPendingUnobservation(e){this.flags_=re(this.flags_,8,e)}get diffValue(){return+!!D(this.flags_,16)}set diffValue(e){this.flags_=re(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Nt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Nt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Mt(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||Mt(e)||Mt(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=Tt(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new jt(e)}return Et(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.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 te(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ComputedValue`,kt);var jt=class{constructor(e){this.cause=void 0,this.cause=e}};function Mt(e){return e instanceof jt}function Nt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(At(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Pt(){return M.trackingDerivation!==null}function Ft(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.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 It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new jt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(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&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=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 Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.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 kt&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(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 dn(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 fn(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 pn=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 D(this.flags_,1)}set isDisposed(e){this.flags_=re(this.flags_,1,e)}get isScheduled(){return D(this.flags_,2)}set isScheduled(e){this.flags_=re(this.flags_,2,e)}get isTrackPending(){return D(this.flags_,4)}set isTrackPending(e){this.flags_=re(this.flags_,4,e)}get isRunning(){return D(this.flags_,8)}set isRunning(e){this.flags_=re(this.flags_,8,e)}get diffValue(){return+!!D(this.flags_,16)}set diffValue(e){this.flags_=re(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Nt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Mt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.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}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}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[O]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.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_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.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 M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=xe(N),kn=xe(`action.bound`,{bound:!0}),An=xe(En,{autoAction:!0}),jn=xe(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,we)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return we(e?An:On,t,r);if(p(t))return bt(t.name||Dn,t,e);if(p(r))return bt(t,r,e);if(m(t))return Mn(xe(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 xt(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 pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(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||de,_=new pn(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=wt(!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`?Ni(t,n):Ni(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&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(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`),_i(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=ne(t);return Fi(()=>{let t=Di(e,i)[O];T(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Ni(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(Ni(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(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 qe(e,Ae)}let or=De(`flow`),sr=De(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Ae(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(_i(e)||pi(e)||Ot(e))i=Pi(e);else if(Ai(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Pi(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(Pi(e),t)}function gr(e,t,n){return qr(Pi(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(Ai(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(Ni(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(_i(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Ai(e)){var r,i;let n=e[O];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Ai(e)||!!e[O]||oe(e)||vn(e)||At(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(Ai(e))return e[O].keys_();if(_i(e)||Si(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Ai(e))return Cr(e).map(t=>e[t]);if(_i(e))return Cr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Ai(e))return Cr(e).map(t=>[t,e[t]]);if(_i(e))return Cr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!Si(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Ai(e)?e[O].set_(t,r):_i(e)?e.set(t,r):Si(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Ai(e)?e[O].delete_(t):_i(e)||Si(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Ai(e))return e[O].has_(t);if(_i(e)||Si(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Ai(e))return e[O].get_(t);if(_i(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Ai(e))return e[O].defineProperty_(t,r);n(39)}function jr(e){if(Ai(e))return e[O].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=Pi(e);if(pi(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(_i(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Si(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Ai(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Pi(e,t),n,r)}function Fr(e,t,n){if(At(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(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(Ot(e)||At(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(Si(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(_i(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){an();try{return e.apply(t)}finally{on()}}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[O].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=bt(n.name+`-effect`,t);var a=Bn(t=>{wt(!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[O]}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=Di(e,t),(n=e[O]).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 Jr(e,t){let r=Ht();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{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(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 Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Di(e,n)[O];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Ai(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Di(e,r)[O];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(O),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(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)}ji(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[O];return t===O?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):E(si,t)?si[t]:e[t]},set(e,t,n){let r=e[O];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=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 ae(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){Ft(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=Jr(this,{object:this.proxy_,type:ni,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=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(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){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,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 oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,O,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[O];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[O];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[O].spliceWithArray_(e,t,n)},push(...e){let t=this[O];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[O].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[O];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[O],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[O];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[O];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[O];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 fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[O])}let mi={},hi=`delete`;var gi=class{constructor(e,t=fe,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[O]=mi,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_=se(`${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(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Dt(this.has_(e),me,`${this.name_}.${ee(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=Jr(this,{type:n?ri:`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(Ft(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,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&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){Ft(this.keysAtom_),zr(()=>{var n;let r=new Dt(t,this.enhancer_,`${this.name_}.${ee(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=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(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 vi({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 vi({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 _i(e)&&(e=new Map(e)),zr(()=>{g(e)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=yi(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`}},_i=b(`ObservableMap`,gi);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||_i(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 bi={};var xi=class{constructor(e,t=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=bi,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_=se(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{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(Ft(this.atom_),Kr(this)){let t=Jr(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=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(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 Ci({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 Ci({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 Si(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(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`}},Si=b(`ObservableSet`,xi);function Ci(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let wi=Object.create(null),Ti=`remove`;var Ei=class{constructor(e,t=new Map,r,i=Ve){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 ae(`${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 kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,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&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!E(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return E(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(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Dt(e in this.target_,me,`${this.name_}.${ee(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);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(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{on()}return!0}defineObservableProperty_(e,t,n,r=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=ki(e),s={configurable:M.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 Dt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(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=ki(e),o={configurable:M.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 kt(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(Ft(this.keysAtom_),!E(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;an();let r=Yr(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 Dt&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ti,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(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&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),T(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Di(e,t){if(t&&Ai(e)&&n(`Options can't be provided for already observable objects.`),E(e,O))return Pi(e)instanceof Ei||n(`Cannot convert '${P(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,O,new Ei(e,new Map,String(r),nt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[O]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ve(t)&&E(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 Ni(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[O].atom_;if(Si(e))return e.atom_;if(_i(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,P(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,P(e)),i}if(oe(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[O]))return e[O];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(oe(e)||At(e)||vn(e)||_i(e)||Si(e))return e;if(e[O])return e[O];n(24,e)}function P(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(zn(e))return e.name;else n=Ai(e)||_i(e)||Si(e)?Pi(e):Ni(e);return n.name_}function Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(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(!(E(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||_i(e)||C(e)||Si(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:P},$mobx:O}),e.$mobx=O,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=xi,e.Reaction=pn,e._allowStateChanges=wt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=Ct,e._getAdministration=Pi,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Pt,e._resetGlobalState=Qt,e._startAction=St,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=de,e.compareIdentity=ce,e.compareShallow=ue,e.compareStructural=le,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=se,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Ni,e.getDebugName=P,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=Ot,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=_i,e.isObservableObject=Ai,e.isObservableProp=Sr,e.isObservableSet=Si,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=ut,e.observableDeep=ct,e.observableRef=ot,e.observableShallow=st,e.observableStruct=lt,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=_e,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=Vt,e.values=wr,e.when=Br})),X=Ee(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=pH():t.exports=mH()}))();function hH(e,t){let n=gH(e),r=n.copy();return r.style=Mf(n.style,t),r}function gH(e){if(!(e instanceof K))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function _H(e){return{fn:(t=>hH(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function vH(e){return{fn:((t,n)=>hH(n,new U({[e]:H.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function yH(e,t){return new U({[e]:t})}function bH(){let e={};for(let t of wf)e[t]=_H(yH(t,!0)),e[`not_${t}`]=_H(yH(t,!1));for(let[t,n]of Object.entries(Ef))e[t]=_H(yH(n,!0));return e}const xH={fn:((e,t)=>hH(t,U.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},SH={fn:((e,t)=>hH(t,new U({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function CH(){return{fg:vH(`color`),bg:vH(`bgcolor`),...bH(),link:SH,style:xH}}function wH(e,t){let n;try{n=$l(e.trim())}catch(n){throw n instanceof Fl?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 TH(n,t,JSON.stringify(e))}function TH(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 EH(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function DH(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 OH=EH([`string`,`int`],((e,t)=>Ru(wH(e,`darken`),t).hex)),kH=EH([`string`,`int`],((e,t)=>Ru(wH(e,`lighten`),-t).hex)),AH={min:0,max:100,note:`0 = from, 100 = toward`},jH=EH([`string`,`string`,`float`],((e,t,n)=>eu(wH(e,`mix`),wH(t,`mix`),DH(n,`mix`,`percentage`,AH)/100).hex)),MH={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},NH=EH([`string`],(e=>Hu(wH(e,`contrastOn`)).hex)),PH={depth:V.TRUECOLOR},FH=e=>EH([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uu(wH(t,`readableOn`),wH(n,`readableOn`),DH(r,`readableOn`,`ratio`,MH),i,void 0,a).hex})),IH={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function LH(){let e={};for(let[t,n]of Object.entries(IH)){let r=t;e[n]=EH([`string`,`float`],((e,t)=>{let i={...yu,[r]:DH(t,n,`amount`)};return ju.fromRgba(wH(e,n)).applyKey(i).toRgba().hex}))}return e}function RH(e=()=>PH){return{darken:OH,lighten:kH,mix:jH,contrastOn:NH,readableOn:FH(e),...LH()}}function zH(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:TH(Fu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function BH(e){return{color:{fn:(t=>Fu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Tp(cf(n),zH(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const VH=Mp.play(0);function HH(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}const UH={...v_.loops,typewriter:e=>v_.transitions.typewriter(e).effect,scramble:e=>v_.transitions.scramble(e).effect,backspace:e=>v_.transitions.backspace(e).effect,scrambleOut:e=>v_.transitions.scrambleOut(e).effect};function WH(e){if(!Object.hasOwn(UH,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(UH).map(e=>JSON.stringify(e)).join(`, `)}`);return UH[e]}function GH(e,t={}){let n=t.timeline??(()=>VH),r=(e,t,r)=>[Mp.run(n(),t),ff(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=mp(a,o,i);return i.onHold?.(hp(s,o)),s.value},a=(e,t)=>Mp.run(Mp.play(e),t);return{frames:{fn:((...t)=>{let n=HH(`frame`,t,gH).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return b_(...r(`frames`,new y_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=HH(`color`,e,e=>wH(e,`stepped`));return t[i(`stepped`,yf(t.map(e=>e.seconds)))].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`},tween:{fn:((e,t,n,r,o)=>i(`tween`,a(n,wp(r,o,{seconds:e,ease:cf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,G.continuous(bf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=WH(t),s=gH(i),c=s.plain,l=e();return b_(...r(`glyphs`,a(n,Xg(s,o({z:yh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function KH(e){return{...CH(),...RH(e)}}new U({color:`red`,dim:!0});const qH=/^(?:(?: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,JH=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function YH(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(qH);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(JH);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 XH(e){let t=e.match(JH);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 ZH(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 QH(e){return e.toLocaleString()}function $H(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 eU(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 tU=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],nU=tU.length;function rU(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*(nU-1));o+=tU[t]}return o}function iU(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 aU(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 oU=ny(),sU=[...wy];function cU(){return{basename:{fn:e=>ne(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>D(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>ZH(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(sI(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>oI(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>cI(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>oU,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>sU,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(aU(`sparkline`,[`width`],n),rU(iU(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>eU(e,$H(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function lU(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const uU=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>lU(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function dU(){return{formatInteger:{fn:e=>QH(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>YH(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>XH(e),argTypes:[`string`],arity:{kind:`exact`}}}}let fU=null;function pU(e,t){if(fU!==null)throw Error(`a draw is already in progress: draws do not nest`);let n={at:e,timeline:t,frame:{time:e,onHold:({nextChange:e})=>{n.soonest=Math.min(n.soonest,e)}},soonest:1/0};return fU=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{fU=null}}}function mU(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(fU===null)throw Error(`the clock was read outside a draw (${e})`);return fU}const hU={now:()=>He(mU(`now`).at),frame:()=>mU(`frame`).frame,timeline:()=>mU(`timeline`).timeline};function gU(e,t){let{frames:n,stepped:r}=GH(e,t===void 0?{}:{timeline:t});if(n===void 0||r===void 0)throw Error(`rich-js's animationFuncs no longer registers frames and stepped`);return{frames:n,stepped:r}}const _U=new Set([`now`,`ago`]);function vU(e,t){return Object.fromEntries(Object.entries(KE(e)).filter(([e])=>_U.has(e)===t))}const yU=vU(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),bU=[e=>vU(e.now,!0),e=>gU(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(gU(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),uU];function xU(e){return Object.assign({},...e.map(e=>e(hU)))}const SU=new Set(Object.keys(xU(bU)));function CU(e){return new Set([...SU,...Object.keys(xU(e))])}const wU={readableOn:FH};function TU(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return OT({fromString:e=>new K(e),toString:e=>e.plain,isT:e=>e instanceof K,missingKey:`error`,funcs:{...eD(),...hk(),...HD(),...uO(),...IT(),...gD(),...mD(),...yU,...KH(r),...Object.fromEntries(Object.entries(wU).map(([e,t])=>[e,t(r)])),...xU([...bU,...e.clockFuncs??[]]),...cU(),...dU(),...n??{}}})}function EU({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...JF(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=AR(e=>{let i=HR(e,t)?Object.keys(n):zR(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=AR(n=>i(n).flatMap(n=>[...FR(n,t).keys()].map(t=>({path:t,reaches:ZR(t,e)}))));return{ofTemplate:a,calls:AR(e=>new Set(i(e).flatMap(e=>[...WR(e,t)]))),ofVariable:t=>[...$y(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...Zy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function DU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const OU=new WeakMap;function kU(e){let t=OU.get(e);return t===void 0&&(t=EU({names:new Set([...XR(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),OU.set(e,t)),t}function AU(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const jU=new WeakMap;function MU(e){let t=jU.get(e);return t===void 0&&(t=PU(e),jU.set(e,t)),t}function NU(e){return MU(e).projections}function PU(e){let t=new Map(XR(e)),n=new Map,r={reads:kU(e),projections:n,clock:SU};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=DU(e,r),i=t===void 0?null:kk(t);i&&n.set(e,`reads the draw's "${i}" (${Ok[i]})`)}let i=IU(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=AU(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of sy)if(!a.has(t))for(let n of i[t]){let i=AU(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=DU(r,i);if(t===void 0||n.has(r))continue;let o=jk(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function FU(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>sy.flatMap(n=>{let r=t[n];return cy(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function IU(e){let t=FU(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function LU(e,t){return AU(e,MU(t))}function RU(e){return t=>AU(t,e)!==null}const zU={nested:e=>`${e} sets "distribution" on a container inside a row — the row's own container places every cell along it, through any { h } or { v } nested in it, so this one would place nothing. Set it on the row (the outermost 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 BU(e,t){let n=new Map;for(let e of Object.keys(t)){let t=OS(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:q(e.source,[`presets`])})}function VU(e,t){let n=[[`root`,e.root],...Object.entries(e.presets??{}).map(([e,t])=>[`presets.${e}.root`,t.root])];for(let[e,r]of n)if(r!==void 0){for(let[n,i]of aS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const HU=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${vk(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${UU(vk(r.definition),n)}${WU(t,n)}`:`${e} entry "${t}" does not match any declared segment${WU(t,n)}`;function UU(e,t){let n=Object.keys(t).filter(yk(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function WU(e,t){return nI(e)+Sk(e,e=>Object.hasOwn(t,e))}function GU(e,t,n,r){let i=[[[`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,r,a]of i){if(r===void 0||cy(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Ey(r)?rH(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(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:q(e.source,[`globals`,`preset`])}),BU(e,t.presets);let a=$R(t);for(let t of a.names)t!==`settings`&&!t.startsWith(JU)||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:q(e.source,[`variables`,t])});let o=(t,n,i)=>{ZP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" ${ZP(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:i}),QP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" 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:i});let a=s(t,`bar`);a!==void 0&&e.issues.push({path:n,message:zU[a](n),line:i});let o=new Map;for(let e of Wy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=By(e);o.set(t,[...o.get(t)??[],e])}for(let[t,r]of o){if(r.length<2)continue;let a=r[1].name,s=Hy(a,new Set(o.keys()));e.issues.push({path:n,message:`${n} has ${r.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: "${a}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:i})}};function s(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`nested`)return`nested`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||zy[e.direction]===`cell`);return zy[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:zy[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Gy(t,n)]):e.opens===void 0?[]:[[e.opens.body,Ky(t)]];function*u(e,t){for(let[n,r]of e){let e=s(n,t);e!==void 0&&(yield[e,r]),yield*u(l(n,r),c(n,t))}}let d=new Set,f=(n,i)=>{let o=iS(n),s=eS(n)?Object.entries(n.rows).map(([e,t])=>[t,`${i}.rows.${e}`]):l(o,i);for(let[t,n]of u(s,c(o,`bar`)))e.issues.push({path:n,message:zU[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of aS(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(uW(e,`${s}.when`,o.when,a,{line:n}),cW(e,`${s}.when`,o.when,n),lW(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(YP(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${Li}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Li}"`,line:n});continue}let c=r(o.name);lH(c)&&(d.add(o.name),e.unplaced.push({path:s,message:HU(i,o.name,t.segments,c),line:n})),nW(e,t,o,s,n)}};n.root!==void 0&&f(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&f(t.root,`presets.${e}.root`);let p=new Map([[`root`,rS(t.root)]]);for(let e of hS(t.presets)){let{node:n,path:r}=vS(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of qy(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);lH(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:HU(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}vW(e,t,a,()=>!0)}const KU=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function qU(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!hS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${hS(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(`, `)})${nI(i)}`,line:c})},p=new Set(Vy(vS(t,a).node)),m=(r,i)=>{!tI.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${nI(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 JU=`settings.`;function YU(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>JU+e)])}}function XU(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=$U(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of cb(n,QU(n)))i(e,`the defaults do not stand together: ${t}`)}function ZU(e){return $U(e).length>0||cb(e,QU(e)).length>0}function QU(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function $U(e){let t=t=>sb(eW(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||sb(eW(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${tW(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 eW(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function tW(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&sb(n)!==void 0).map(([e])=>e)}function nW(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=ob(a),s=`${r}: placement "${By(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(`, `)})`:lb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?$v(a):``}, but it must be ${fb(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])=>lb(o[e],t))||ZU(o)))for(let{message:t}of cb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function rW(e,t,n,r,i){for(let[a,o]of $y(n))uW(e,`${t}.${a}`,o,r,{segCtx:i})}function iW(e,t,n,r,i){if(!(!Zy(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:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const aW=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function oW(e,t,n,r){if(!Zy(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=LU(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${aW}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=NU(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${aW}`,line:i(`depends_on`)})})}}function sW(e,t){let n=new Map(XR(t)),r=kU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=sy.find(e=>Ak[e]===n||Ak[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${Ak[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=DU(e,a),s=o===void 0?void 0:jk(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of FU(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function cW(e,t,n,r){try{gk.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function lW(e,t,n,r,i,a=t.helpers,o){let s=n.slice(n.lastIndexOf(`.`)+1);for(let{name:c,site:l,via:u}of zR(r,a)){if(Object.prototype.hasOwnProperty.call(t.actions,c))continue;let r=l===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(u!==null){fW(e,u,`Template references unknown action "${c}"${r}`,dW(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function uW(e,t,n,r,i){for(let[a,o]of FR(n,r.helpers)){if(QR(a,r))continue;if(a.startsWith(JU)){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??q(e.source,t.split(`.`))});continue}if(o!==null){fW(e,o,`Template references unknown variable ".${a}"${xI(a)}`,dW(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&QR(n,r)?` (segment-local vars are namespaced — write ".${n}")`:xI(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function dW(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function fW(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function pW(e,t,n,r,i){let a=n.set,o=rC(Mx[r].configKey),s=`${a} takes ${BS(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:q(e.source,[`actions`,t,`min`])});return}let c=gW(n,i);if(c===hW){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:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!zS(o,e.value,i));if(l.length!==0){if(a===Mx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Ey(e.value)))){let r=Mx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:rH(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(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:q(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<=mW?r.join(`, `):`${r.slice(0,mW).join(`, `)} and ${r.length-mW} 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:q(e.source,[`actions`,t,n])})}}}const mW=3,hW=Symbol(`any integer`);function gW(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?ES(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)}]:hW}function _W(e,t){return Object.entries(e).filter(([e])=>t(e))}function vW(e,t,n,r){let i=fF(t),a=TS(i);for(let[n,o]of _W(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 ${DS(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ix.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:q(e.source,[`actions`,n,`set`])});let s=Bx.get(o.set);s!==void 0&&pW(e,n,o,s,i)}for(let[n,i]of _W(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&&XF(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:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of _W(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of _W(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=IC(r);if(o===null){let t=wC(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${TC().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:q(e.source,[`actions`,n,a])});continue}let s=KU.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:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){qU(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!hS(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: ${hS(t.presets).join(`, `)})`,line:q(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${$v(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(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(`, `)})${nI(o.segment)}`,line:q(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:q(e.source,[`actions`,n,a])})}}for(let[i,a]of _W(t.variables,r)){rW(e,`variables.${i}`,a,n);let t=bI(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of _W(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))rW(e,`segments.${i}.vars.${t}`,r,n,i);let r=ob(a);if(XU(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=YU({...n,helpers:o},r);for(let n of Cz){let c=a[n];typeof c==`string`&&(uW(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),lW(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of _W(t.variables,r))iW(e,`variables.${i}`,a,n),oW(e,`variables.${i}`,a,t);sW(e,t);for(let[i,a]of _W(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))iW(e,`segments.${i}.vars.${r}`,o,n,i),oW(e,`segments.${i}.vars.${r}`,o,t)}function yW(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=bW(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:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function bW(e){let t=new Map,n=new Map,r=kU(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function xW(e,t,n){let r=new Map([...YR(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, a control the bar builds, or the daemon's payload), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function SW(e){return{...jW,config:ZF(jW.raw,e)}}function CW(e,t,n,r,i){let a=RW(e,t,i,(t,a)=>{let o=dz(uz(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>kW(t,n,r,e,i)),s=hz(o,r.beneath.dropped);return{inherited:new Set([...mL(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=gz(ZF(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(tz)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const wW=new WeakMap;function TW(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,DW(e.path)])]),a=wW.get(n)??new Map;wW.set(n,a);let o=JSON.stringify([t.repo,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=dz(e,t,{config:n,rendering:new Map},(e,t,n)=>kW(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function EW(e,t,n,r){return dz(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>kW(e,t,n,`<plugin install>`,void 0)).dropped}function DW(e){try{let t=s.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function OW(e,t,n,r,i,a=e=>s.readFileSync(e,`utf-8`),o){let c={repo:i.repo,checkout:i.cwd===null?null:Kz(i.cwd),home:e.home},l=Vz(e,c.repo),u=TW(l.definitions,c,n,o),d={...u,dropped:[...u.dropped,...l.strays]};r.warned(l.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:e,scope:n}of t){let t=p.at(-1)?.plugins,i=CW(e,a(e),p.at(-1)?.config??f,{...c,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??d.rendering}},o);r.warned(i.warnings),p.push({...i,path:e})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));r.warned(g.map(tz));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:c.checkout,roots:l.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(MW(SW(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(MW(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())MW(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function kW(e,t,n,r,i){if(n){MW(AW(e),new Map,r,i);return}let a=yk(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(vW(s,e,$R(e),a),yW(s,e,a),xW(s,e,{checked:a,authored:a}),o.length>0)throw new pb(r,o)}function AW(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const jW={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function MW(e,t,n=`<config>`,r=new Set(ny()),i=[]){let a=cH(e.config.segments,t),o=PW({...e,path:n},i,a),s=(t,s)=>{let c=yS(e.config,t,o.authored);return NW(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof pb)||o.cells.length===0)throw e;let t=s([],[]),n=new Set(t.dropped.flatMap(e=>e.issues.map(e=>e.message))),{taken:r,refused:i}=o.cells.reduce((e,t)=>{try{return s([...e.taken,t],[]),{...e,taken:[...e.taken,t]}}catch(r){if(!(r instanceof pb))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,bS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function NW({raw:e,source:t},n,r,i,a,o,s,c){let l=[],u={source:t,issues:l,allowedPalettes:r,groups:[],unplaced:[],inherited:[]},d=()=>{if(l.length>0)throw new pb(n,[...l,...u.unplaced,...u.inherited],c)};GU(u,a,e,o),yW(u,a),d();let f=IW(n,a.segments,u,o,i,s),p=nH(dH(a),l);d();let m=Xte(Pte(p)),h=new Set([...YR({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return xW(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function PW(e,t,n){let r=[...t].reverse().concat(e),i=uH(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>lH(n(e.seg)),c=e=>(e.raw.insert??[]).filter(a);return{cells:r.flatMap(e=>c(e).filter(o)),authored:{root:r.some(e=>e.raw.root!==void 0),presets:new Set(r.flatMap(e=>Object.keys(e.raw.presets??{})))},dropped:r.flatMap(t=>{let r=mb(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:HU(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function FW(e){if(e.length>0)throw new Aee(e)}function IW(e,t,n,r,i,a){let o=new Map,s=(e,t)=>{o.set(e,[...o.get(e)??[],t])};for(let{file:e,issue:t}of a)s(e,t);for(let t of n.unplaced)s(e,t);for(let{name:a,...o}of n.inherited){let n=i.flatMap(e=>{let t=VU(e.raw,a);return t===void 0?[]:[{layer:e,...t}]})[0];n===void 0?s(e,o):s(n.layer.path,{path:n.path,message:HU(n.layoutKey,a,t,r(a)),line:q(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new kee(e,t))}function LW(e,t,n=new Set(ny()),r=zW){return RW(e,t,n,()=>({inherited:r,layer:null})).raw}function RW(e,t,n,r){let i=BW(e,t),a=Fee(e,t),o=[...a===null?[]:[a],...Ik(e,t,bb(i)&&bb(i.variables)?Object.keys(i.variables):[])],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(ny()),groups:[],unplaced:[],inherited:[]};if(!bb(i))throw new pb(e,[{path:``,message:`Config root must be an object, got ${xb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:UW({...c,issues:[]},i.plugins)??[],bb(i.segments)?Object.keys(i.segments):[]),d=VW(c,i,l,kL(e),e);if(s.length>0)throw new pb(e,s,o);return{raw:d,warnings:o,layer:u}}const zW=new Set;function BW(e,t){try{return Ia.default.parse(t)}catch(t){let n=t;throw new pb(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function VW(e,t,n,r,i){for(let n of Object.keys(t))HW.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...HW].join(`, `)}`,line:q(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=vC(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=EI(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=hL(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.
|
|
182
|
+
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),_V;if(n.kind===`group`){let r=xb(e,RV,t,n);return r===null?_V:(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}),BV(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:q(e.source,[`root`])}),_V}if(a){let r=xb(e,EV,t,n);return r===null?_V:{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=xb(e,DV,t,n);return r===null?_V:{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=xb(e,OV,t,n);return r===null?_V:{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:q(e.source,[`root`])}),_V};function AV(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Xx.source},additionalProperties:{$ref:gV}},parse:(e,t,n,r)=>{let i=r[n];if(!yb(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${bb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Xx.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:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=kV(e,`${t}.${n}.${r}`,o)}return a}}}const jV={noun:`root key`,fields:{rows:AV(),when:Ob(),distribution:CV()}};function MV(e,t,n){return yb(n)&&`rows`in n?xb(e,jV,t,n)??{rows:{}}:kV(e,t,n)}const NV={noun:`insert key`,fields:{seg:TV(),id:dL(),before:Ob(),after:Ob()}};function PV(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=xb(e,NV,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(Ii(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return Ii(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${bb(t)}`,line:q(e.source,[`insert`])}),[])}function FV(){return{required:!0,json:{type:`string`,pattern:Xx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Xx.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 "${gi}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function IV(){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 ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function LV(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=hb(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:q(e.source,[...t.split(`.`),n])});return}return i}}}}const RV={noun:`layout-node key`,fields:{kind:vV(`group`),name:FV(),label:LV(),open:kb(),direction:Pb(Ly),key:IV(),bg:Ob(),fg:Ob(),when:Ob(),distribution:CV(),children:xV(Db(()=>kV))}};function zV(e){return e.key??`groups.`+e.name}function BV(e){let t=ji+e.name;return Si(t,{variable:t,key:zV(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function VV(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function HV(e,t){Nk(e,t,ji,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&VV(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}.`)&&zV(t)===zV(r)&&VV(e,t.path,`group "${t.name}" shares key "${zV(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=zV(t);if(i.has(n)||i.set(n,gi),t.open===!0){let r=i.get(n);r!==`closed`&&VV(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=ji+e.name,r=zV(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Oi(r,i.get(r)),o[t]=ki(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 UV=`menu`,WV=`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`,GV=e=>e.kind===`call`&&e.name===`dict`,KV=e=>e.kind===`literal`&&typeof e.value!=`object`,qV=e=>yi(``,e,2)===void 0;function JV(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&&GV(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(GV))return t(`whose options (dict …) is not its last argument — ${WV}`);if(i!==void 0&&a===void 0&&!KV(i)&&qV(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=yi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${WV}`);let c=a===void 0?{}:nD(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=IS(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Mk(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 "${AS(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 YV(e){let t=OT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===UV).map(JV)}catch{return`parse-failed`}}function XV(e,t){let n=YV(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:kS(t,e.apply,e.options.key),member:OS(e.apply)}]:[])}function ZV(e){let t=OT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(UV)}catch{return!1}}function QV(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function $V(e,t){Nk(e,t,Mi,`{{ menu }} helpers`),Nk(e,t,Ni,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))ZV(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:q(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`&&ZV(i)&&QV(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.`)}for(let[n,i]of Object.entries(r.partials??{}))ZV(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of Uy(rS(t.root)))typeof n.when==`string`&&ZV(n.when)&&QV(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||!ZV(r))continue;let n=YV(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:eH(r.apply);n!==void 0&&QV(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function eH(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(OS(e)===`closed`)return`whose apply action is named "${gi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function tH(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 mS(e.presets)){let a=new Map,s=new Map;for(let c of Uy(_S(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,YV(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=zy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||eH(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=OS(i),f=kS(u,i,l.key),p=MS(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=jS(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]=ki(f,d),n[f]=Oi(f,gi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function nH(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const rH={noun:`style key`,fields:{hueShift:Ab(),chromaScale:Ab({min:0}),lightnessScale:Ab(),lightnessShift:Ab()}};function iH(e,t){if(!yb(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${bb(t)}`,line:q(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:q(e.source,[`styles`,r])});continue}if(Ty(r)){e.issues.push({path:`styles.${r}`,message:nH(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=xb(e,rH,`styles.${r}`,i);t!==null&&(n[r]={...yu,...t})}return n}const aH={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:MV(e,`${t}.${n}`,r[n])},globals:{required:!1,json:yC(),parse:(e,t,n,r)=>r[n]===void 0?void 0:vC(e,`${t}.${n}`,r[n])}}};function oH(e,t){if(!yb(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${bb(t)}`,line:q(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:q(e.source,[`presets`,r])});continue}let t=xb(e,aH,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function sH(e,t){let n=[...t].map(([e,t])=>[yk(e),t]);return t=>{if(YP(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=xk(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function cH(e){return e.kind===`plugin`||e.kind===`missing`}function lH(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>$x(e)?Object.values(e.rows):[e],o=[e.root,...Object.values(e.presets).flatMap(e=>e.root===void 0?[]:[e.root])];for(let e of o.flatMap(a))for(let t of Uy(e))t.kind===`segment`&&i(zy(t),{seg:t.name});for(let e of t)i(e.id??e.seg,{seg:e.seg,anchor:e.anchor});let s=new Set,c=e=>n(e.seg).kind===`absent`||e.anchor!==void 0&&s.has(e.anchor);for(let e=!0;e;){e=!1;for(let[t,n]of r)!s.has(t)&&n.every(c)&&(s.add(t),e=!0)}return e=>s.has(e)}function uH(e){let t=0,n=sH(e.segments,new Map),r=e=>{let r=n(e).kind===`declared`;return r||(t+=1),r},i=e=>({...e,children:e.children.flatMap(e=>a(e))}),a=e=>e.kind===`container`?[i(e)]:r(e.name)?[Hy(e,i)]:[],o=e=>a(e)[0]??dH,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>$x(e)?s(e):o(e),l=e=>e.root===void 0?e:{...e,root:c(e.root)},u={...e,root:s(e.root),presets:Object.fromEntries(Object.entries(e.presets).map(([e,t])=>[e,l(t)]))};return t===0?e:u}const dH={kind:`container`,direction:`horizontal`,children:[]};var fH=Ee((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()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(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 Lt.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=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(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:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return _e(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(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 w(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:_e(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 T(e,t){return{t:e,i:t,o:ee,u:te}}function ee(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)||!Ye(e.h[t]))&&this.u(e,t,n,!1)===null?0:Ye(n.value)?1:(It(r,t,ne(e,0,0,n,!1,!1)),2)}function te(e,t,n,r){let i=ne(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function E(e,t,n){var r;let{name:i,addInitializer:a}=n;return Ye(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 ne(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Ye(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 D(e,t){return{t:e,i:t,o:re,u:ie}}function re(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ie(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function O(e,t,n){function r(e){let n=Pt({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=St(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&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 ae(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ce(e,t,n){function r(e,t){let n=St(e)[j];return(n.V??=new Map).set(o,()=>new _n(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[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function le(e){return{t:Jt,i:e,o:ue,u:de}}function ue(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=Ve(n.set)?n.set:_e(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(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?nn:sn;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 de(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:_e(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?nn:sn).u(e,t,n,r))}function fe(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function pe(e){return e||Xt}function me(e){return fe(e,ce)}function he(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 ge(e){return fe(e,O)}function _e(e,t,n=!1,r){function i(){return ve(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ve(e,t,n,r,i){let a=ye(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{be(a)}}function ye(e,t){let n=N.trackingDerivation,r=!t||!n;k();let i=N.allowStateChanges;r&&De();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function be(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Ne(),e.R&&Oe(e.k),N.suppressReactionErrors=!1}function xe(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 Se(e){return e instanceof xn}function Ce(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=De(),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 Oe(t),!0}if(e.K===2)return Oe(t),!0}}return ke(e),Oe(t),!1}}}function we(e,t,n){ke(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&&je(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Ae(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Te(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)je(t[n],e);e.K=-1}function Ee(e){let t=De();try{return e()}finally{Oe(t)}}function De(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Oe(e){N.trackingDerivation=e}function ke(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Ae(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function je(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Me(e))}function Me(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function k(){N.inBatch++}function Ne(){--N.inBatch===0&&(Ie(),!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 yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Pe(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Pe))}function Fe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Me(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 A(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 Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){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 Re(e){return fe(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?_e(t.name||`<unnamed action>`,t,e):r(n)?_e(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ve(0,!1,e,this,void 0)}function Ve(e){return r(e)&&!0===e.isMobxAction}function He(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ue(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 Ue(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function We(e,t,n,i){let a=typeof i==`function`?Tt(t,n):Tt(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 Ge(e,t,n,r){let i=Ut(t);return Ot(()=>{let t=St(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ke(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(Ke)),t}function qe(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),qe)),t}function Je(e){r(e.cancel)&&e.cancel()}function Ye(e){return!0===e?.isMobXFlow}function Xe(e,t){var n;if(t===void 0)return bn(e);if(!1===wt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Tt(e,t)):!1}function Ze(e,t){if(!e)return!1;if(t!==void 0){if(wt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return wt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function Qe(e){return Ze(e)}function $e(e){return wt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):yt(e)?e.map((e,t)=>t):void t(5)}function et(e,n){return wt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):yt(e)?n>=0&&n<e.length:void t(10)}function tt(e){if(wt(e))return e[j].it();t(38)}function nt(e,t,n){if(bn(e)){let r,i=!0;return He(()=>{let a=e.get();if(!i||n){let n=De();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Oe(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),ft(e,t)}function rt(e,t,n){return e.set(t,n),n}function it(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Qe(e))return e;if(vn(e)||bn(e))return it(e.get(),t);if(t.has(e))return t.get(e);if(yt(e)){let n=rt(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=it(e,t)}),n}if(sr(e)){let n=rt(t,e,new Set);return e.forEach(e=>{n.add(it(e,t))}),n}if(ir(e)){let n=rt(t,e,new Map);return e.forEach((e,r)=>{n.set(r,it(e,t))}),n}{let n=rt(t,e,{});return tt(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=it(e[r],t))}),n}}function at(e,t){k();try{return e.apply(t)}finally{Ne()}}function ot(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=_e(`When-effect`,t);var a=He(t=>{xe(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function st(e){return e[j]}function ct(e){return e.st!==void 0&&e.st.length>0}function lt(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 ut(e,n){let r=De();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{Oe(r)}}function dt(e){return e.ot!==void 0&&e.ot.length>0}function ft(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 pt(e,t){let n=De(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Oe(n)}}function mt(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!==Lt;){let t=Ft(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 ht(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function gt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function _t(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function vt(e){return function(){let t=this[j];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 yt(e){return a(e)&&er(e[j])}function bt(e){return e[Symbol.toStringTag]=`MapIterator`,Mt(e)}function xt(e){return e[Symbol.toStringTag]=`SetIterator`,Mt(e)}function St(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,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 M[r]??(M[r]=le({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Ct(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function wt(e){return!!a(e)&&dr(e[j])}function Tt(e,n){if(typeof e==`object`&&e){if(yt(e))return n!==void 0&&t(23),e[j].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,Dt(e)),r}if(wt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Dt(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Et(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Et(Tt(e,n))}function Dt(e,t){let n;if(t!==void 0)n=Tt(e,t);else{if(Ve(e))return e.name;n=wt(e)||ir(e)||sr(e)?Et(e):Tt(e)}return n.tt}function Ot(e){let t=De();k();try{return e()}finally{Ne(),Oe(t)}}function kt(e,t,n=-1){return At(e,t,n)}function At(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=jt(e),t=jt(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(!At(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)||!At(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function jt(e){return yt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Mt(e){return e[Symbol.iterator]=Nt,Pt(Object.create(pr),e)}function Nt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Pt=Object.assign,Ft=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=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 Fe(this)}reportChanged(){k(),A(this),Ne()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=le(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=ae(`observable`),Qt=ae(`observable.ref`,{A:y}),$t=ae(`observable.shallow`,{A:function(e,t,n){return e==null||wt(e)||yt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=ae(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=pe(t);return new _n(e,he(n),n.name,!0,n.equals)},array(e,t){let n=pe(t);return function(e,t,n=`ObservableArray`,r=!1){return Ot(()=>{let i=new Qn(n,t,r);It(i.j,j,{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,he(n),n.name)},map(e,t){let n=pe(t);return new rr(e,he(n),n.name)},set(e,t){let n=pe(t);return new or(e,he(n),n.name)},object:(e,t,n)=>Ot(()=>Ge(function(e,t){var n;return(n=(e=St(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=me(Qt),rn=me($t),an=me(Zt),on=me(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?ce(Zt,e,t):Qe(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=D(cn),un=ge(D(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return O(ln,e,t);if(o(e))return ge(D(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Pt(dn,ln);let pn=0,mn=1,hn=(fn=Ft(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){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(ct(this)){let t=ut(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(),dt(this)&&pt(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 vn=l(`ObservableValue`,_n);var yn=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=_e(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,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(Fe(this),Ce(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(Pe)}else Ce(this)&&(this.Nt(),k(),this.rt=this.Rt(!1),Ne());let e=this.rt;if(Se(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||Se(e)||Se(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=we(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||(Te(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`,yn);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),Ie())}X(){if(!this.isDisposed){k(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,Ce(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Ne()}}track(e){if(this.isDisposed)return;k(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=we(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Te(this),Se(n)&&this.Pt(n.cause),Ne()}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||(k(),Te(this),Ne()))}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[j]=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=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(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=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return E(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&&Je(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Je(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=fe(Wn,E),qn={has:(e,t)=>st(e).et(t),get:(e,t)=>st(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=st(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=st(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=st(e).l(t,n))==null||r},ownKeys:e=>st(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?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[j];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 Wt(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=Rt),ct(this)){let r=ut(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;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=dt(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&&pt(this,i)}Ft(e,t,n){let r=dt(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&&pt(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(ct(this)){let n=ut(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[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];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[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];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[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};ht(`at`,gt),ht(`concat`,gt),ht(`flat`,gt),ht(`includes`,gt),ht(`indexOf`,gt),ht(`join`,gt),ht(`lastIndexOf`,gt),ht(`slice`,gt),ht(`toString`,gt),ht(`toLocaleString`,gt),ht(`toSorted`,gt),ht(`toSpliced`,gt),ht(`with`,gt),ht(`every`,_t),ht(`filter`,_t),ht(`find`,_t),ht(`findIndex`,_t),ht(`findLast`,_t),ht(`findLastIndex`,_t),ht(`flatMap`,_t),ht(`forEach`,_t),ht(`map`,_t),ht(`some`,_t),ht(`toReversed`,_t),ht(`reduce`,vt),ht(`reduceRight`,vt);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[j]=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,Ot(()=>{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 _n(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(ct(this)){let r=ut(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(ct(this)&&!ut(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=dt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return at(()=>{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&&pt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}}Jt(e,t){at(()=>{var n;let r=new _n(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=dt(this);n&&pt(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 bt({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 bt({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)),at(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.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(){at(()=>{Ee(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return at(()=>{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[j]=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),Ot(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){at(()=>{Ee(()=>{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(ct(this)){let t=ut(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){at(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=dt(this);t&&pt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=dt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return at(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return xt({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 xt({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)?at(()=>{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=Yt){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 Wt(`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 yn)return n.set(t),!0;if(ct(this)){let n=ut(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=dt(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&&pt(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 _n(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{k();let r=this.Dt(e);if(!r)return r;if(ct(this)){let n=ut(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=Pt({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Ne()}return!0}S(e,t,n,r=!1){try{k();let i=this.Dt(e);if(!i)return i;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Ct(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 It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Ne()}return!0}m(e,t,n=!1){try{k();let r=this.Dt(e);if(!r)return r;if(ct(this)&&!ut(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=Ct(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 It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Ne()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;k();let r=dt(this),i=this.j.get(e),a;if(i||!r||(a=Ft(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 _n&&(a=i.rt),A(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&pt(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Ne()}return!0}Yt(e,t){var n;let r=dt(this);r&&r&&pt(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(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=xe,e._allowStateChangesInsideComputed=Be,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=be,e._getAdministration=Et,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||yt(e)||vn(e)?r=Et(e):wt(e)&&(r=Et(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=ye,e.action=In,e.actionBound=Rn,e.autorun=He,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return kt(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,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(wt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return wt(e)?$e(e).map(t=>[t,e[t]]):ir(e)?$e(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):yt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ge,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(et(e,n))return wt(e)?e[j].Tt(n):ir(e)?e.get(n):yt(e)?e[n]:void t(11)},e.getAtom=Tt,e.getDebugName=Dt,e.getDependencyTree=function(e,t){return Ke(Tt(e,t))},e.getObserverTree=function(e,t){return qe(Tt(e,t))},e.has=et,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return lt(Et(e,t),n)}(e,t,n):function(e,t){return lt(Et(e),t)}(e,t)},e.isAction=Ve,e.isBoxedObservable=vn,e.isComputed=function(e){return Xe(e)},e.isComputedProp=function(e,t){return Xe(e,t)},e.isFlow=Ye,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=Qe,e.isObservableArray=yt,e.isObservableMap=ir,e.isObservableObject=wt,e.isObservableProp=function(e,t){return Ze(e,t)},e.isObservableSet=sr,e.keys=$e,e.makeAutoObservable=function(e,t,n){return o(e)?Ge(e,e,t,n):(Ot(()=>{let r=St(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>mt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return Ot(()=>{let r=St(e,n)[j];Ht(t).forEach(e=>mt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return nt(Et(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Et(e);if(yt(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)&&!wt(e))return nt(r,t,n);return ft(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return We(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return We(`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=qt,e.ownKeys=tt,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=xe(!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=Ue(n),d,f=!0,p=!1,m=n.equals||Kt,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){wt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):yt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Be,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){k();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Ne()}return}wt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):yt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),k(),r>=n.length&&(n.length=r+1),n[r]=i,Ne()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return it(e,new Map)},e.transaction=at,e.untracked=Ee,e.values=function(e){return wt(e)?$e(e).map(t=>e[t]):ir(e)?$e(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):yt(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 Pt(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ot(e,n,Pt({},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):ot(e,t,n||{})}})),pH=Ee((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++M.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=E(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 x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function ee(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function te(e){return e===null?null:typeof e==`object`?``+e:e}function E(e,t){return o.hasOwnProperty.call(e,t)}let ne=Object.getOwnPropertyDescriptors;function D(e,t){return!!(e&t)}function re(e,t,n){return n?e|=t:e&=~t,e}function ie(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let O=Symbol(`mobx administration`);var ae=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 D(this.flags_,1)}set isBeingObserved(e){this.flags_=re(this.flags_,1,e)}get isPendingUnobservation(){return D(this.flags_,2)}set isPendingUnobservation(e){this.flags_=re(this.flags_,2,e)}get diffValue(){return+!!D(this.flags_,4)}set diffValue(e){this.flags_=re(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let oe=b(`Atom`,ae);function se(e,t=f,n=f){let r=new ae(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ce(e,t){return e===t}function le(e,t){return Li(e,t)}function ue(e,t){return Li(e,t,1)}let de=Object.is;function fe(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?ut.array(e,{name:n}):g(e)?ut.object(e,void 0,{name:n}):x(e)?ut.map(e,{name:n}):C(e)?ut.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function pe(e,t,r){if(e==null||Ai(e)||pi(e)||_i(e)||Si(e))return e;if(Array.isArray(e))return ut.array(e,{name:r,deep:!1});if(g(e))return ut.object(e,void 0,{name:r,deep:!1});if(x(e))return ut.map(e,{name:r,deep:!1});if(C(e))return ut.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function me(e){return e}function he(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ge=`override`,_e={annotationType_:ge,make_:ye,extend_:be};function ve(e){return e.annotationType_===ge}function ye(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),E(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function be(e,t,r,i){n(44,this.annotationType_)}function xe(e,t){return{annotationType_:e,options_:t,make_:Se,extend_:Ce}}function Se(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,Ee(e,this,t,n,!1)),2)}function Ce(e,t,n,r){let i=Ee(e,this,t,n);return e.defineProperty_(t,i,r)}function we(e,t,r){ie(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>bt(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 Te(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 Ee(e,t,n,r,i=M.safeDescriptors){var a,o;Te(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:bt(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 De(e,t){return{annotationType_:e,options_:t,make_:Oe,extend_:ke}}function Oe(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&&(!E(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Me(e,this,t,n,!1,!1)),2)}function ke(e,t,n,r){let i=Me(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Ae(e,t,n){var r;ie(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 je(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 Me(e,t,n,r,i,a=M.safeDescriptors){je(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 k(e,t){return{annotationType_:e,options_:t,make_:Ne,extend_:Pe}}function Ne(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Pe(e,t,n,i){return A(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Fe(e,t,n){ie(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 kt(o)}return o(function(){let e=Di(this)[O],n=this,r=e.values_.get(a);r instanceof kt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[O],n=e.values_.get(a);if(n instanceof kt&&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 A(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 Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??fe,r)}function ze(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ie(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[O];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??fe,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[O]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[O]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(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 Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.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?ot:ut;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 Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(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?ot:ut).extend_(e,t,n,r))}function qe(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 Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:me}),Qe=Ie(`observable.shallow`,{enhancer_:pe}),$e=Ie(`observable.struct`,{enhancer_:he});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?fe:e.deep===!1?me:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??fe:fe}function it(e,t,n){return t&&typeof t.kind==`string`?ze(Xe,e,t):xr(e)?e:g(e)?ut.object(e,t,n):Array.isArray(e)?ut.array(e,t):x(e)?ut.map(e,t):C(e)?ut.set(e,t):typeof e==`object`&&e?e:ut.box(e,t)}let at={box(e,t){let n=Ye(t);return new Dt(e,tt(n),n.name,!0,n.equals)},array(e,t){let n=Ye(t);return oi(e,tt(n),n.name)},map(e,t){let n=Ye(t);return new gi(e,tt(n),n.name)},set(e,t){let n=Ye(t);return new xi(e,tt(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Fe)}let pt=k(dt),mt=ft(k(`computed.struct`,{equals:le})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Fe(pt,e,t);if(g(e))return ft(k(dt,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 kt(r)};r(ht,pt);let gt=0,_t=1,vt=i(()=>{},`name`)?.configurable??!1,yt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function bt(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 xt(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),vt&&(yt.value=e,a(o,`name`,yt)),o}function xt(e,t,n,r,i){let a=St(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Ct(a)}}function St(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=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Tt(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:_t++,parentActionId_:gt};return gt=d.actionId_,d}function Ct(e){gt!==e.actionId_&&n(30),gt=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Et(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function wt(e,t){let n=Tt(e);try{return t()}finally{Et(n)}}function Tt(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Et(e){M.allowStateChanges=e}var Dt=class extends ae{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=de){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!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(Ft(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,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 te(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Ot=b(`ObservableValue`,Dt);var kt=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 jt(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_=bt(this.name_+`-setter`,e.set)),this.equals_=e.equals||de,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return D(this.flags_,1)}set isComputing(e){this.flags_=re(this.flags_,1,e)}get isRunningSetter(){return D(this.flags_,2)}set isRunningSetter(e){this.flags_=re(this.flags_,2,e)}get isBeingObserved(){return D(this.flags_,4)}set isBeingObserved(e){this.flags_=re(this.flags_,4,e)}get isPendingUnobservation(){return D(this.flags_,8)}set isPendingUnobservation(e){this.flags_=re(this.flags_,8,e)}get diffValue(){return+!!D(this.flags_,16)}set diffValue(e){this.flags_=re(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Nt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Nt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Mt(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||Mt(e)||Mt(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=Tt(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new jt(e)}return Et(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.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 te(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ComputedValue`,kt);var jt=class{constructor(e){this.cause=void 0,this.cause=e}};function Mt(e){return e instanceof jt}function Nt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(At(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Pt(){return M.trackingDerivation!==null}function Ft(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.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 It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new jt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(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&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=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 Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.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 kt&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(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 dn(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 fn(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 pn=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 D(this.flags_,1)}set isDisposed(e){this.flags_=re(this.flags_,1,e)}get isScheduled(){return D(this.flags_,2)}set isScheduled(e){this.flags_=re(this.flags_,2,e)}get isTrackPending(){return D(this.flags_,4)}set isTrackPending(e){this.flags_=re(this.flags_,4,e)}get isRunning(){return D(this.flags_,8)}set isRunning(e){this.flags_=re(this.flags_,8,e)}get diffValue(){return+!!D(this.flags_,16)}set diffValue(e){this.flags_=re(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Nt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Mt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.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}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}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[O]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.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_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.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 M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=xe(N),kn=xe(`action.bound`,{bound:!0}),An=xe(En,{autoAction:!0}),jn=xe(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,we)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return we(e?An:On,t,r);if(p(t))return bt(t.name||Dn,t,e);if(p(r))return bt(t,r,e);if(m(t))return Mn(xe(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 xt(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 pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(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||de,_=new pn(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=wt(!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`?Ni(t,n):Ni(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&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(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`),_i(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=ne(t);return Fi(()=>{let t=Di(e,i)[O];T(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Ni(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(Ni(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(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 qe(e,Ae)}let or=De(`flow`),sr=De(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Ae(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(_i(e)||pi(e)||Ot(e))i=Pi(e);else if(Ai(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Pi(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(Pi(e),t)}function gr(e,t,n){return qr(Pi(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(Ai(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(Ni(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(_i(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Ai(e)){var r,i;let n=e[O];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Ai(e)||!!e[O]||oe(e)||vn(e)||At(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(Ai(e))return e[O].keys_();if(_i(e)||Si(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Ai(e))return Cr(e).map(t=>e[t]);if(_i(e))return Cr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Ai(e))return Cr(e).map(t=>[t,e[t]]);if(_i(e))return Cr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!Si(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Ai(e)?e[O].set_(t,r):_i(e)?e.set(t,r):Si(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Ai(e)?e[O].delete_(t):_i(e)||Si(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Ai(e))return e[O].has_(t);if(_i(e)||Si(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Ai(e))return e[O].get_(t);if(_i(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Ai(e))return e[O].defineProperty_(t,r);n(39)}function jr(e){if(Ai(e))return e[O].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=Pi(e);if(pi(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(_i(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Si(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Ai(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Pi(e,t),n,r)}function Fr(e,t,n){if(At(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(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(Ot(e)||At(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(Si(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(_i(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){an();try{return e.apply(t)}finally{on()}}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[O].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=bt(n.name+`-effect`,t);var a=Bn(t=>{wt(!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[O]}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=Di(e,t),(n=e[O]).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 Jr(e,t){let r=Ht();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{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(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 Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Di(e,n)[O];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Ai(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Di(e,r)[O];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(O),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(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)}ji(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[O];return t===O?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):E(si,t)?si[t]:e[t]},set(e,t,n){let r=e[O];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=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 ae(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){Ft(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=Jr(this,{object:this.proxy_,type:ni,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=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(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){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,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 oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,O,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[O];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[O];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[O].spliceWithArray_(e,t,n)},push(...e){let t=this[O];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[O].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[O];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[O],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[O];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[O];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[O];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 fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[O])}let mi={},hi=`delete`;var gi=class{constructor(e,t=fe,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[O]=mi,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_=se(`${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(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Dt(this.has_(e),me,`${this.name_}.${ee(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=Jr(this,{type:n?ri:`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(Ft(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,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&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){Ft(this.keysAtom_),zr(()=>{var n;let r=new Dt(t,this.enhancer_,`${this.name_}.${ee(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=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(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 vi({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 vi({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 _i(e)&&(e=new Map(e)),zr(()=>{g(e)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=yi(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`}},_i=b(`ObservableMap`,gi);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||_i(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 bi={};var xi=class{constructor(e,t=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=bi,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_=se(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{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(Ft(this.atom_),Kr(this)){let t=Jr(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=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(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 Ci({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 Ci({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 Si(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(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`}},Si=b(`ObservableSet`,xi);function Ci(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let wi=Object.create(null),Ti=`remove`;var Ei=class{constructor(e,t=new Map,r,i=Ve){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 ae(`${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 kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,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&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!E(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return E(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(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Dt(e in this.target_,me,`${this.name_}.${ee(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);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(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{on()}return!0}defineObservableProperty_(e,t,n,r=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=ki(e),s={configurable:M.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 Dt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(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=ki(e),o={configurable:M.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 kt(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(Ft(this.keysAtom_),!E(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;an();let r=Yr(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 Dt&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ti,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(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&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),T(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Di(e,t){if(t&&Ai(e)&&n(`Options can't be provided for already observable objects.`),E(e,O))return Pi(e)instanceof Ei||n(`Cannot convert '${P(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,O,new Ei(e,new Map,String(r),nt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[O]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ve(t)&&E(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 Ni(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[O].atom_;if(Si(e))return e.atom_;if(_i(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,P(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,P(e)),i}if(oe(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[O]))return e[O];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(oe(e)||At(e)||vn(e)||_i(e)||Si(e))return e;if(e[O])return e[O];n(24,e)}function P(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(zn(e))return e.name;else n=Ai(e)||_i(e)||Si(e)?Pi(e):Ni(e);return n.name_}function Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(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(!(E(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||_i(e)||C(e)||Si(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:P},$mobx:O}),e.$mobx=O,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=xi,e.Reaction=pn,e._allowStateChanges=wt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=Ct,e._getAdministration=Pi,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Pt,e._resetGlobalState=Qt,e._startAction=St,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=de,e.compareIdentity=ce,e.compareShallow=ue,e.compareStructural=le,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=se,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Ni,e.getDebugName=P,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=Ot,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=_i,e.isObservableObject=Ai,e.isObservableProp=Sr,e.isObservableSet=Si,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=ut,e.observableDeep=ct,e.observableRef=ot,e.observableShallow=st,e.observableStruct=lt,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=_e,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=Vt,e.values=wr,e.when=Br})),X=Ee(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=fH():t.exports=pH()}))();function mH(e,t){let n=hH(e),r=n.copy();return r.style=Mf(n.style,t),r}function hH(e){if(!(e instanceof K))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function gH(e){return{fn:(t=>mH(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function _H(e){return{fn:((t,n)=>mH(n,new U({[e]:H.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function vH(e,t){return new U({[e]:t})}function yH(){let e={};for(let t of wf)e[t]=gH(vH(t,!0)),e[`not_${t}`]=gH(vH(t,!1));for(let[t,n]of Object.entries(Ef))e[t]=gH(vH(n,!0));return e}const bH={fn:((e,t)=>mH(t,U.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},xH={fn:((e,t)=>mH(t,new U({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function SH(){return{fg:_H(`color`),bg:_H(`bgcolor`),...yH(),link:xH,style:bH}}function CH(e,t){let n;try{n=$l(e.trim())}catch(n){throw n instanceof Fl?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 wH(n,t,JSON.stringify(e))}function wH(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 TH(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function EH(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 DH=TH([`string`,`int`],((e,t)=>Ru(CH(e,`darken`),t).hex)),OH=TH([`string`,`int`],((e,t)=>Ru(CH(e,`lighten`),-t).hex)),kH={min:0,max:100,note:`0 = from, 100 = toward`},AH=TH([`string`,`string`,`float`],((e,t,n)=>eu(CH(e,`mix`),CH(t,`mix`),EH(n,`mix`,`percentage`,kH)/100).hex)),jH={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},MH=TH([`string`],(e=>Hu(CH(e,`contrastOn`)).hex)),NH={depth:V.TRUECOLOR},PH=e=>TH([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uu(CH(t,`readableOn`),CH(n,`readableOn`),EH(r,`readableOn`,`ratio`,jH),i,void 0,a).hex})),FH={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function IH(){let e={};for(let[t,n]of Object.entries(FH)){let r=t;e[n]=TH([`string`,`float`],((e,t)=>{let i={...yu,[r]:EH(t,n,`amount`)};return ju.fromRgba(CH(e,n)).applyKey(i).toRgba().hex}))}return e}function LH(e=()=>NH){return{darken:DH,lighten:OH,mix:AH,contrastOn:MH,readableOn:PH(e),...IH()}}function RH(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:wH(Fu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function zH(e){return{color:{fn:(t=>Fu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Tp(cf(n),RH(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const BH=Mp.play(0);function VH(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}const HH={...v_.loops,typewriter:e=>v_.transitions.typewriter(e).effect,scramble:e=>v_.transitions.scramble(e).effect,backspace:e=>v_.transitions.backspace(e).effect,scrambleOut:e=>v_.transitions.scrambleOut(e).effect};function UH(e){if(!Object.hasOwn(HH,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(HH).map(e=>JSON.stringify(e)).join(`, `)}`);return HH[e]}function WH(e,t={}){let n=t.timeline??(()=>BH),r=(e,t,r)=>[Mp.run(n(),t),ff(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=mp(a,o,i);return i.onHold?.(hp(s,o)),s.value},a=(e,t)=>Mp.run(Mp.play(e),t);return{frames:{fn:((...t)=>{let n=VH(`frame`,t,hH).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return b_(...r(`frames`,new y_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=VH(`color`,e,e=>CH(e,`stepped`));return t[i(`stepped`,yf(t.map(e=>e.seconds)))].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`},tween:{fn:((e,t,n,r,o)=>i(`tween`,a(n,wp(r,o,{seconds:e,ease:cf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,G.continuous(bf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=UH(t),s=hH(i),c=s.plain,l=e();return b_(...r(`glyphs`,a(n,Xg(s,o({z:yh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function GH(e){return{...SH(),...LH(e)}}new U({color:`red`,dim:!0});const KH=/^(?:(?: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,qH=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function JH(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(KH);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(qH);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 YH(e){let t=e.match(qH);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 XH(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 ZH(e){return e.toLocaleString()}function QH(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 $H(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 eU=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],tU=eU.length;function nU(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*(tU-1));o+=eU[t]}return o}function rU(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 iU(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 aU=ty(),oU=[...Cy];function sU(){return{basename:{fn:e=>ne(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>D(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>XH(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(oI(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>aI(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>sI(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>aU,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>oU,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(iU(`sparkline`,[`width`],n),nU(rU(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>$H(e,QH(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function cU(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const lU=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>cU(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function uU(){return{formatInteger:{fn:e=>ZH(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>JH(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>YH(e),argTypes:[`string`],arity:{kind:`exact`}}}}let dU=null;function fU(e,t){if(dU!==null)throw Error(`a draw is already in progress: draws do not nest`);let n={at:e,timeline:t,frame:{time:e,onHold:({nextChange:e})=>{n.soonest=Math.min(n.soonest,e)}},soonest:1/0};return dU=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{dU=null}}}function pU(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(dU===null)throw Error(`the clock was read outside a draw (${e})`);return dU}const mU={now:()=>He(pU(`now`).at),frame:()=>pU(`frame`).frame,timeline:()=>pU(`timeline`).timeline};function hU(e,t){let{frames:n,stepped:r}=WH(e,t===void 0?{}:{timeline:t});if(n===void 0||r===void 0)throw Error(`rich-js's animationFuncs no longer registers frames and stepped`);return{frames:n,stepped:r}}const gU=new Set([`now`,`ago`]);function _U(e,t){return Object.fromEntries(Object.entries(KE(e)).filter(([e])=>gU.has(e)===t))}const vU=_U(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),yU=[e=>_U(e.now,!0),e=>hU(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(hU(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),lU];function bU(e){return Object.assign({},...e.map(e=>e(mU)))}const xU=new Set(Object.keys(bU(yU)));function SU(e){return new Set([...xU,...Object.keys(bU(e))])}const CU={readableOn:PH};function wU(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return OT({fromString:e=>new K(e),toString:e=>e.plain,isT:e=>e instanceof K,missingKey:`error`,funcs:{...eD(),...hk(),...HD(),...uO(),...IT(),...gD(),...mD(),...vU,...GH(r),...Object.fromEntries(Object.entries(CU).map(([e,t])=>[e,t(r)])),...bU([...yU,...e.clockFuncs??[]]),...sU(),...uU(),...n??{}}})}function TU({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...qF(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=kR(e=>{let i=VR(e,t)?Object.keys(n):RR(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=kR(n=>i(n).flatMap(n=>[...PR(n,t).keys()].map(t=>({path:t,reaches:XR(t,e)}))));return{ofTemplate:a,calls:kR(e=>new Set(i(e).flatMap(e=>[...UR(e,t)]))),ofVariable:t=>[...Qy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...Xy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function EU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const DU=new WeakMap;function OU(e){let t=DU.get(e);return t===void 0&&(t=TU({names:new Set([...YR(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),DU.set(e,t)),t}function kU(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const AU=new WeakMap;function jU(e){let t=AU.get(e);return t===void 0&&(t=NU(e),AU.set(e,t)),t}function MU(e){return jU(e).projections}function NU(e){let t=new Map(YR(e)),n=new Map,r={reads:OU(e),projections:n,clock:xU};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=EU(e,r),i=t===void 0?null:kk(t);i&&n.set(e,`reads the draw's "${i}" (${Ok[i]})`)}let i=FU(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=kU(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of oy)if(!a.has(t))for(let n of i[t]){let i=kU(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=EU(r,i);if(t===void 0||n.has(r))continue;let o=jk(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function PU(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>oy.flatMap(n=>{let r=t[n];return sy(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function FU(e){let t=PU(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function IU(e,t){return kU(e,jU(t))}function LU(e){return t=>kU(t,e)!==null}const RU={nested:e=>`${e} sets "distribution" on a container inside a row — the row's own container places every cell along it, through any { h } or { v } nested in it, so this one would place nothing. Set it on the row (the outermost 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 zU(e,t){let n=new Map;for(let e of Object.keys(t)){let t=DS(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:q(e.source,[`presets`])})}function BU(e,t){let n=[[`root`,e.root],...Object.entries(e.presets??{}).map(([e,t])=>[`presets.${e}.root`,t.root])];for(let[e,r]of n)if(r!==void 0){for(let[n,i]of iS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const VU=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${vk(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${HU(vk(r.definition),n)}${UU(t,n)}`:`${e} entry "${t}" does not match any declared segment${UU(t,n)}`;function HU(e,t){let n=Object.keys(t).filter(yk(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function UU(e,t){return tI(e)+Sk(e,e=>Object.hasOwn(t,e))}function WU(e,t,n,r){let i=[[[`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,r,a]of i){if(r===void 0||sy(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Ty(r)?nH(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(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:q(e.source,[`globals`,`preset`])}),zU(e,t.presets);let a=QR(t);for(let t of a.names)t!==`settings`&&!t.startsWith(qU)||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:q(e.source,[`variables`,t])});let o=(t,n,i)=>{ZP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" ${ZP(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:i}),QP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" 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:i});let a=s(t,`bar`);a!==void 0&&e.issues.push({path:n,message:RU[a](n),line:i});let o=new Map;for(let e of Uy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=zy(e);o.set(t,[...o.get(t)??[],e])}for(let[t,r]of o){if(r.length<2)continue;let a=r[1].name,s=Vy(a,new Set(o.keys()));e.issues.push({path:n,message:`${n} has ${r.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: "${a}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:i})}};function s(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`nested`)return`nested`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||Ry[e.direction]===`cell`);return Ry[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Ry[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Wy(t,n)]):e.opens===void 0?[]:[[e.opens.body,Gy(t)]];function*u(e,t){for(let[n,r]of e){let e=s(n,t);e!==void 0&&(yield[e,r]),yield*u(l(n,r),c(n,t))}}let d=new Set,f=(n,i)=>{let o=rS(n),s=$x(n)?Object.entries(n.rows).map(([e,t])=>[t,`${i}.rows.${e}`]):l(o,i);for(let[t,n]of u(s,c(o,`bar`)))e.issues.push({path:n,message:RU[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of iS(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(lW(e,`${s}.when`,o.when,a,{line:n}),sW(e,`${s}.when`,o.when,n),cW(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(YP(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${Li}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Li}"`,line:n});continue}let c=r(o.name);cH(c)&&(d.add(o.name),e.unplaced.push({path:s,message:VU(i,o.name,t.segments,c),line:n})),tW(e,t,o,s,n)}};n.root!==void 0&&f(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&f(t.root,`presets.${e}.root`);let p=new Map([[`root`,nS(t.root)]]);for(let e of mS(t.presets)){let{node:n,path:r}=_S(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Ky(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);cH(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:VU(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}_W(e,t,a,()=>!0)}const GU=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function KU(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!mS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${mS(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(`, `)})${tI(i)}`,line:c})},p=new Set(By(_S(t,a).node)),m=(r,i)=>{!eI.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${tI(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 qU=`settings.`;function JU(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>qU+e)])}}function YU(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=QU(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of sb(n,ZU(n)))i(e,`the defaults do not stand together: ${t}`)}function XU(e){return QU(e).length>0||sb(e,ZU(e)).length>0}function ZU(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function QU(e){let t=t=>ob($U(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||ob($U(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${eW(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 $U(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function eW(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&ob(n)!==void 0).map(([e])=>e)}function tW(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=ab(a),s=`${r}: placement "${zy(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(`, `)})`:cb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Qv(a):``}, but it must be ${db(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])=>cb(o[e],t))||XU(o)))for(let{message:t}of sb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function nW(e,t,n,r,i){for(let[a,o]of Qy(n))lW(e,`${t}.${a}`,o,r,{segCtx:i})}function rW(e,t,n,r,i){if(!(!Xy(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:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const iW=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function aW(e,t,n,r){if(!Xy(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=IU(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${iW}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=MU(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${iW}`,line:i(`depends_on`)})})}}function oW(e,t){let n=new Map(YR(t)),r=OU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=oy.find(e=>Ak[e]===n||Ak[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${Ak[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=EU(e,a),s=o===void 0?void 0:jk(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of PU(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function sW(e,t,n,r){try{gk.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function cW(e,t,n,r,i,a=t.helpers,o){let s=n.slice(n.lastIndexOf(`.`)+1);for(let{name:c,site:l,via:u}of RR(r,a)){if(Object.prototype.hasOwnProperty.call(t.actions,c))continue;let r=l===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(u!==null){dW(e,u,`Template references unknown action "${c}"${r}`,uW(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function lW(e,t,n,r,i){for(let[a,o]of PR(n,r.helpers)){if(ZR(a,r))continue;if(a.startsWith(qU)){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??q(e.source,t.split(`.`))});continue}if(o!==null){dW(e,o,`Template references unknown variable ".${a}"${bI(a)}`,uW(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&ZR(n,r)?` (segment-local vars are namespaced — write ".${n}")`:bI(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function uW(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function dW(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function fW(e,t,n,r,i){let a=n.set,o=nC(jx[r].configKey),s=`${a} takes ${zS(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:q(e.source,[`actions`,t,`min`])});return}let c=hW(n,i);if(c===mW){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:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!RS(o,e.value,i));if(l.length!==0){if(a===jx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Ty(e.value)))){let r=jx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:nH(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(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:q(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<=pW?r.join(`, `):`${r.slice(0,pW).join(`, `)} and ${r.length-pW} 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:q(e.source,[`actions`,t,n])})}}}const pW=3,mW=Symbol(`any integer`);function hW(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?TS(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)}]:mW}function gW(e,t){return Object.entries(e).filter(([e])=>t(e))}function _W(e,t,n,r){let i=fF(t),a=wS(i);for(let[n,o]of gW(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 ${ES(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Fx.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:q(e.source,[`actions`,n,`set`])});let s=zx.get(o.set);s!==void 0&&fW(e,n,o,s,i)}for(let[n,i]of gW(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&&YF(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:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of gW(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of gW(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=FC(r);if(o===null){let t=CC(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${wC().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:q(e.source,[`actions`,n,a])});continue}let s=GU.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:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){KU(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!mS(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: ${mS(t.presets).join(`, `)})`,line:q(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${Qv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(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(`, `)})${tI(o.segment)}`,line:q(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:q(e.source,[`actions`,n,a])})}}for(let[i,a]of gW(t.variables,r)){nW(e,`variables.${i}`,a,n);let t=yI(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of gW(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))nW(e,`segments.${i}.vars.${t}`,r,n,i);let r=ab(a);if(YU(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=JU({...n,helpers:o},r);for(let n of Sz){let c=a[n];typeof c==`string`&&(lW(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),cW(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of gW(t.variables,r))rW(e,`variables.${i}`,a,n),aW(e,`variables.${i}`,a,t);oW(e,t);for(let[i,a]of gW(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))rW(e,`segments.${i}.vars.${r}`,o,n,i),aW(e,`segments.${i}.vars.${r}`,o,t)}function vW(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=yW(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:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function yW(e){let t=new Map,n=new Map,r=OU(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function bW(e,t,n){let r=new Map([...JR(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, a control the bar builds, or the daemon's payload), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function xW(e){return{...AW,config:XF(AW.raw,e)}}function SW(e,t,n,r,i){let a=LW(e,t,i,(t,a)=>{let o=uz(lz(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>OW(t,n,r,e,i)),s=mz(o,r.beneath.dropped);return{inherited:new Set([...pL(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=hz(XF(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(ez)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const CW=new WeakMap;function wW(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,EW(e.path)])]),a=CW.get(n)??new Map;CW.set(n,a);let o=JSON.stringify([t.repo,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=uz(e,t,{config:n,rendering:new Map},(e,t,n)=>OW(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function TW(e,t,n,r){return uz(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>OW(e,t,n,`<plugin install>`,void 0)).dropped}function EW(e){try{let t=s.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function DW(e,t,n,r,i,a=e=>s.readFileSync(e,`utf-8`),o){let c={repo:i.repo,checkout:i.cwd===null?null:Gz(i.cwd),home:e.home},l=Bz(e,c.repo),u=wW(l.definitions,c,n,o),d={...u,dropped:[...u.dropped,...l.strays]};r.warned(l.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:e,scope:n}of t){let t=p.at(-1)?.plugins,i=SW(e,a(e),p.at(-1)?.config??f,{...c,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??d.rendering}},o);r.warned(i.warnings),p.push({...i,path:e})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));r.warned(g.map(ez));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:c.checkout,roots:l.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(jW(xW(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(jW(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())jW(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function OW(e,t,n,r,i){if(n){jW(kW(e),new Map,r,i);return}let a=yk(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(_W(s,e,QR(e),a),vW(s,e,a),bW(s,e,{checked:a,authored:a}),o.length>0)throw new fb(r,o)}function kW(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const AW={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function jW(e,t,n=`<config>`,r=new Set(ty()),i=[]){let a=sH(e.config.segments,t),o=NW({...e,path:n},i,a),s=(t,s)=>{let c=vS(e.config,t,o.authored);return MW(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof fb)||o.cells.length===0)throw e;let t=s([],[]),n=new Set(t.dropped.flatMap(e=>e.issues.map(e=>e.message))),{taken:r,refused:i}=o.cells.reduce((e,t)=>{try{return s([...e.taken,t],[]),{...e,taken:[...e.taken,t]}}catch(r){if(!(r instanceof fb))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,yS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function MW({raw:e,source:t},n,r,i,a,o,s,c){let l=[],u={source:t,issues:l,allowedPalettes:r,groups:[],unplaced:[],inherited:[]},d=()=>{if(l.length>0)throw new fb(n,[...l,...u.unplaced,...u.inherited],c)};WU(u,a,e,o),vW(u,a),d();let f=FW(n,a.segments,u,o,i,s),p=tH(uH(a),l);d();let m=Xte(Pte(p)),h=new Set([...JR({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return bW(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function NW(e,t,n){let r=[...t].reverse().concat(e),i=lH(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>cH(n(e.seg)),c=e=>(e.raw.insert??[]).filter(a);return{cells:r.flatMap(e=>c(e).filter(o)),authored:{root:r.some(e=>e.raw.root!==void 0),presets:new Set(r.flatMap(e=>Object.keys(e.raw.presets??{})))},dropped:r.flatMap(t=>{let r=pb(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:VU(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function PW(e){if(e.length>0)throw new jee(e)}function FW(e,t,n,r,i,a){let o=new Map,s=(e,t)=>{o.set(e,[...o.get(e)??[],t])};for(let{file:e,issue:t}of a)s(e,t);for(let t of n.unplaced)s(e,t);for(let{name:a,...o}of n.inherited){let n=i.flatMap(e=>{let t=BU(e.raw,a);return t===void 0?[]:[{layer:e,...t}]})[0];n===void 0?s(e,o):s(n.layer.path,{path:n.path,message:VU(n.layoutKey,a,t,r(a)),line:q(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Aee(e,t))}function IW(e,t,n=new Set(ty()),r=RW){return LW(e,t,n,()=>({inherited:r,layer:null})).raw}function LW(e,t,n,r){let i=zW(e,t),a=Iee(e,t),o=[...a===null?[]:[a],...Ik(e,t,yb(i)&&yb(i.variables)?Object.keys(i.variables):[])],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(ty()),groups:[],unplaced:[],inherited:[]};if(!yb(i))throw new fb(e,[{path:``,message:`Config root must be an object, got ${bb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:HW({...c,issues:[]},i.plugins)??[],yb(i.segments)?Object.keys(i.segments):[]),d=BW(c,i,l,OL(e),e);if(s.length>0)throw new fb(e,s,o);return{raw:d,warnings:o,layer:u}}const RW=new Set;function zW(e,t){try{return Ia.default.parse(t)}catch(t){let n=t;throw new fb(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function BW(e,t,n,r,i){for(let n of Object.keys(t))VW.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...VW].join(`, `)}`,line:q(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=_C(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=TI(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=mL(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.
|
|
183
183
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
184
184
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
185
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=NV(e,`root`,t.root)),t.insert!==void 0&&(a.insert=FV(e,t.insert,i)),t.actions!==void 0&&(a.actions=DL(e,t.actions,r)),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:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=aH(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=_C(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=sH(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=xC(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=EL(e,t.helpers)),t.plugins!==void 0&&(a.plugins=UW(e,t.plugins)),UV(e,a),eH(e,a),Jk(e,a),Nk(e,a,P,`the global settings menu`),Pk(e,a,n),a}const HW=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function UW(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 ${xb(t)}`,line:q(e.source,[`plugins`])})}const WW={},GW=AN(`commands.`),KW=IN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),qW=wN(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),JW=`{{ ${dA} }}`,YW={min:0,max:100,step:5},XW={warnAt:{label:`warning at %`,domain:YW,default:50},errorAt:{label:`error at %`,domain:{...YW,atLeast:`warnAt`},default:80}};function ZW(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:YW,default:80}}}const QW={globals:{palette:`tokyo-night`},variables:{...GW.variables,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:`? `},"glyph.worktree":{kind:`literal`,value:`⊫`},...qW.variables,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.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"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:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"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},"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 main checkout's path, shortened fish-style — `~` under home — plus the subpath and, in a linked worktree, the worktree's name. Click to copy the full path.",template:`{{ $dir := ternary .location.main .current_dir (ne .location.main "") }}{{ if and (ne .home "") (or (eq .home $dir) (hasPrefix (printf "%s/" .home) $dir)) }}{{ $dir = printf "~%s" (trimPrefix .home $dir) }}{{ end }}{{ $text := printf "%s%s" (abbreviatePath $dir) .location.subpath }}{{ if ne .location.worktree "" }}{{ $text = printf "%s (%s %s)" $text .glyph.worktree .location.worktree }}{{ end }}{{ action "copyDir" $text }}`,fg:JW},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 ne .git.branch "" }}{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}{{ end }}{{ if or .location.noRepo ${qW.armed} }}{{ if ne .git.branch "" }} {{ end }}${qW.template}{{ end }}`,fg:JW,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:vN(``).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:GW.template,when:GW.when},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:ZW(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:ZW(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:XW,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:XW,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) ${Ov} }}`,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 }}`},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:KW.template,bg:KW.bg,when:KW.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:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...vN(``).actions,...GW.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...qW.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...KW.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:WW,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:`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:`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:`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 }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Ov} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${dA}) 2 (readableOn (color "accent") (bgOf) ${Ov})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Ov}) .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:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ 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 .)) }}`}},$W=new Set([QW.globals.palette,...Object.keys(QW.themeDefaults),...Object.values(QW.segments).map(e=>e.palette)].filter(e=>e!==void 0)),eG=ZF(LW(`<default>`,JSON.stringify(QW),$W),QW),tG=hS(eG.presets);function nG(e){return tG.includes(e)}const rG=Object.freeze({});function iG(e,t){return e.kind===`decided`?t[e.name]??rG:rG}function aG(e,t){return{...e,...Object.fromEntries(Ex.map(n=>[n,e[n]??t[n]]))}}const oG=(e,t)=>Xb(n=>{let{setting:r,on:i,inTmux:a}=Ub[n].switch;return e[r]===i&&(t||!a)});function sG(e,t,n,r){let i=Dx(e);return ty(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function cG(e,t){return gS(t(`preset`),e.globals.preset,e.presets)}function lG(e,t,n){let r=cG(e,t),i=xS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Yx(a.palette,t(`theme`),i.palette),s=aG(i,iG(o,e.themeDefaults));return{...Object.fromEntries(Tx.map(e=>[e,sG(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:py(a.style,t(`style`),s.style,e.styles),effect:Cy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function uG(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?My:Ny;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const dG=Object.entries(Mx),fG=new Set(Px.map(e=>e.sessionKey)),pG=()=>!1;function mG(e,t){return lG(e,e=>fG.has(e)?t(e):null,pG)}const hG=[`preset`,`theme`];function gG(e,t,n){let r=new Set(hG.slice(0,n).map(e=>Mx[e].sessionKey));return lG(e,e=>r.has(e)?t(e):null,pG)}function _G(e,t){let n=Array.from({length:hG.length+1},(n,r)=>gG(e,t,r));return e=>{let t=hG.indexOf(e);return n[t===-1?hG.length:t]}}function vG(e,t,n,r){return e.flatMap(([e,i])=>{let a=uG(t,e);return a===null||a===uG(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function yG(e,t,n){return uG(mG(e,t),n)}function bG(e,t){let n=mG(e,t);return vG(dG,n,_G(e,t),t=>xG(e,n.preset,t.configKey))}function xG(e,t,n){return n in(_S(e.presets,t).globals??{})?FC(t,n):n}function SG(e,t,n){let r=gS(t(Mx.preset.sessionKey),e.globals.preset,e.presets),i=IC(n);return{key:i?.scope===`globals`?xG(e,r,i.field):n,globals:xS(e,r)}}function CG(e,t){let{preset:n}=mG(e,t);return EG(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:db(a,s);return c===void 0||ub(c)===ub(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function wG(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return hS(e.presets).flatMap(n=>{let i=EG(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 cb(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:db(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const TG=new WeakMap;function EG(e,t){let n=TG.get(e)??new Map;TG.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Wy(vS(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=ob(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 DG(e,t){let n=mG(e,t);return{from:n.preset,globals:_S(e.presets,n.preset).globals??{},picks:vG(dG.filter(([e])=>e!==`preset`),n,_G(e,t),e=>e.configKey),placements:CG(e,t)}}function OG(e,t){return lG({...e,globals:{palette:t},presets:{}},()=>null,pG)}function kG(e,t){let n=mG(e,t),r=uG(n,`theme`);if(r===null)return{kind:`rule`};let i=OG(e,r),a=xS(e,n.preset),o=Object.fromEntries(Ex.map(e=>[e,uG(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Ex.some(e=>o[e]!==uG(i,e))}}function AG(e){return{sessionKeys:Px.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...pC(e)?tG.map(t=>FC(t,e)):[],...PC(e)?ny().map(t=>NC(t,e)):[]]}}function jG(e){return new Set(Px.map(e=>e.configKey).filter(t=>AG(t).fileKeys.some(t=>PG(e,NG(t)))))}function MG(e,t,n){let r=bG(e,n),i=new Set(r.map(e=>e.configKey)),a=zx(e=>i.has(Mx[e].configKey)||t.has(Mx[e].configKey)),o=kG(e,n);return{unsaved:r.length+CG(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function NG(e){let t=IC(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return LC(t)}function PG(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&PG(e[n],r)}function FG(e,t,n){let r=Bx.get(n);if(r!==void 0)return yG(e,t,r);for(let[,t]of nb(e))if(t.key===n)return t.default??null;return null}function IG(e,t){let n=DC(e).get(t);return n===void 0?null:String(n)}const LG={inside:()=>[],defaultOf:()=>gi,menus:[]},RG=e=>`${e.key}\0${e.member}`;function zG(e){let t=new Map,n=n=>{let r=`${n.name}\0${By(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:ZV(a,By(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(RG(e))??new Map;n.set(RG(t),t),o.set(RG(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(RG(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of hS(e.presets))d(vS(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Ai(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(RG(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(RG(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(RG(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const BG=new WeakMap;function VG(e){let t=BG.get(e);if(t!==void 0)return t;let n=zG(e);return BG.set(e,n),n}function HG(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function UG(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function WG(e,t,n){let r=(r,i,a)=>{let o=HG(t(r),t=>e.get(r,t),i);(0,X.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const GG=`render-origin`,KG=`client-hints`,qG=`config-override`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},JG=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},YG=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function XG(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}const ZG=new Set([`1`,`true`]),QG=new Set([`0`,`false`,``]);function $G(e,t){let n=wK(e),r=n.scope===`segment-palette`?`string`:kx(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(ZG.has(t))return`true`;if(QG.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function eK(e){try{return s.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function tK(e,t,n){try{if(t===null){s.rmSync(On(e),{force:!0});return}Dn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function nK(e){return/^\s*$/.test(e)?null:Ua(e)}function rK(e,t){return e!==null&&Ga(e,t)!==void 0}function iK(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(iK),...i}}return e}function aK(e){if(!eS(e))return iK(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,iK(t)])),...n}}const oK=QW,sK=oK.segments,cK=oK.presets,lK=oK.root;function uK(e,t,n,r){if(!rK(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function dK(e,t){let n=LC(t);return t.scope===`segment-palette`&&uK(e,[`segments`,t.segment],sK[t.segment],n.join(`.`)),n}function fK(e){return Ua(Qa(e))}function pK(){return Object.entries(lK.rows).map(([e,t])=>{let n=iK(t);return{path:[`root`],fragment:fK({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function mK(e,t){let n=e===null?void 0:Ga(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function hK(e,t){if(t===void 0)return null;let n=aK(t);return{path:e,fragment:fK(n),unit:{path:e,value:n}}}function gK(e,t){let n=[`presets`,t],r=[...n,`root`],i=cK[t];uK(e,n,i,r.join(`.`));let a=mK(e,r)??hK(r,i?.root);return a!==null&&yo(a.fragment)?a:null}function _K(e,t){let n=vo(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 vK(e,t){return[...pK(),mK(e,[`root`]),gK(e,t)].filter(e=>e!==null).reduce(_K,new Map)}function yK(e,t,n){for(let{node:r,...i}of vK(e,t).values())if(xo(r,n))return i;throw new Z(`${bK(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 bK(e,t){return gK(e,t)?.path??[`root`]}function xK(e,t){return t.scope===`preset-root`?bK(e,t.preset):LC(t)}function SK(e,{unit:t}){return t===null?e:fo(e,t.path,Qa(t.value),Xa)}function CK(e){let t=IC(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function wK(e){let t=CK(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function TK(e,t,n,r,i){let a=IK(t,r),o,s=()=>(o??={chain:AK(t,n)}).chain;LK(t,s,a),i(t,s,a),tK(t.path,r,e.logger),e.record(t.path,n,r)}function EK(e,t,n){let r=kK(e,t(),n);if(r.length>0)throw new Z(`refused: ${e.above.map(e=>e.path).join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const DK=()=>{};function OK(e,t){try{return t()}catch(t){throw!(t instanceof Z)||e.above.length===0?t:new Z(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function kK(e,t,n){if(t===null)return[];let r=new Set(PK(NK(t),NK(n)));return PK(MK(e,t),MK(e,n)).filter(e=>!r.has(e))}function AK(e,t){try{return jK(e,t)}catch(e){if(e instanceof pb)return null;throw e}}function jK(e,t){return OW(e.locs,t===null?e.above:[hB(e.path),...e.above],eG,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:s.readFileSync(n,`utf8`))}function MK(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function NK(e){return e.layers.at(-1)?.config??e.base}function PK(e,t,n=``){return!FK(e)||!FK(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>PK(e[r],t[r],n===``?r:`${n}.${r}`))}function FK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function IK(e,t){try{return jK(e,t)}catch(e){throw e instanceof pb?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function LK(e,t,n){if(n.dropped.length===0)return;let r=t();if(r===null)return;let i=e=>e.dropped.flatMap(e=>e.issues.map(t=>({file:e.file,issue:t}))),a=new Set(i(r).map(({file:e,issue:t})=>`${e}\0${t.message}`)),o=i(n).filter(({file:e,issue:t})=>!a.has(`${e}\0${t.message}`));if(o.length>0)throw new Z(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new pb(e,[t]).message).join(`
|
|
186
|
-
`)}`)}function RK(e,t){let n=wK(t),r=nK(eK(e)??``),i=r===null?void 0:Ga(r,LC(n));return i!==void 0&&`value`in i?i.value:void 0}function zK(e,t,n){BK(e,t,n,[])}function BK(e,t,n,r){let i=eK(t.path),a=n.reduce((e,[t,n])=>fo(e,dK(nK(e),wK(t)),$G(t,n),Xa),i??``);TK(e,t,i,OK(t,()=>VK(a,t.path,r,e=>e)),EK)}function VK(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=yK(nK(s),n,i),l=To(SK(s,c),c.path,i,a,Qa(o));if(l===null)throw new Z(`${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 HK(e,t,n){let r=nK(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of vK(r,t)){if(!xo(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qa(e,c):Qa(s.value);if(a!==`#`)return fo(e,[...i,`rows`,a],l,Xa);if(gK(r,t)!==null)throw new Z(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return fo(e,i,l,Xa)}return e}function UK(e,t){return mo(e,t,t[0]===`presets`&&t.length>2&&!nG(t[1])?2:0)}function WK(e,t,n){let r=n.map(CK),i=eK(t.path);if(i===null)return;let a=r.reduce((e,t)=>UK(e,xK(nK(e),t)),i);a!==i&&TK(e,t,i,a,DK)}function GK(e){let t=e===null?void 0:Ga(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function KK(e,t){let n=new Set([...tG,...GK(e),...t.above.flatMap(e=>Object.keys(Ia.default.parse(s.readFileSync(e.path,`utf8`)).presets??{}))].map(OS));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(OS(e)))}function qK(e,t,n,r,i,a){let o=eK(t.path),s=nK(o??``),c=KK(s,t),l=[`presets`,c],u=OK(t,()=>gK(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qa(o??``,u.fragment):Qa(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Qa(r)]]],f=i.map(([e,t])=>{let n=FC(c,e);return[dK(s,wK(n)),$G(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>fo(e,t,n,Xa),fo(o??``,l,`{}`,Xa));return TK(e,t,o,OK(t,()=>VK(p,t.path,a.map(e=>({...e,preset:c})),HK)),EK),c}function JK(e,t,n,r){let i=eK(t.path);TK(e,t,i,fo(i??``,[`themeDefaults`,n],Qa(r),Xa),EK)}function YK(e,t,n){if(nG(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=eK(t.path),a=nK(i??``);if(i===null||a===null||Ga(a,r)===void 0)throw new Z(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ga(a,[`globals`,`preset`]);TK(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>UK(e,t),i),DK)}function XK(e,t,n,r){let i=CK(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=eK(t.path),o=r.op===`remove`?r.target:r.anchor,s=OK(t,()=>yK(nK(a??``),i.preset,o)),c=SK(a??``,s),{after:l,placed:u}=ZK(c,s.path,r,()=>{let e=IK(t,c).config;return hS(e.presets).map(t=>vS(e,t).node)});if(l===null)throw new Z(`${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 TK(e,t,a,l,EK),u}function ZK(e,t,n,r){switch(n.op){case`remove`:return{after:Co(e,t,n.target),placed:null};case`insert`:{let i=Qte(n.segment,n.anchor,r());return{after:wo(e,t,i,n.anchor,n.relation),placed:i}}}}function QK(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 $K={load:()=>new Map,save:()=>{},flush:()=>{}};var eq=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e=$K,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Array.from(this.storage.load(),([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,X.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,X.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,X.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()}close(){this.flush(),this.storage=$K}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 tq(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function nq(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=tq(r);e.ok?n.set(e.id,i):t(r,e.problem)}return n}function rq(e){let t=tq(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const iq={load:()=>new Map,save:()=>{}},aq=new Set(Px.map(e=>e.sessionKey)),oq=e=>aq.has(e)||e.startsWith(Hk),sq=8*1024*1024,cq={past:[],future:[]},lq=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var uq=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=iq){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(n.load())}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??cq;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??cq}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(lq(r));i.set(lq(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:QK(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!oq(i)&&i!==`edit.mode`)){if(i===`edit.mode`){let t=r.get(e);r.set(e,{before:t===void 0?a:t.before,after:o});return}n(e,{kind:`session`,key:i,before:a,after:o})}}),file:(e,t,r,i)=>n(e,{kind:`file`,file:t,before:r,after:i}),wrote:()=>{t=!0},written:()=>t,commit:()=>{let t=new Map(e),n=new Map(r);e.clear(),r.clear();for(let e of new Set([...t.keys(),...n.keys()])){let r=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=r.length===0?i:vq(i,r),o=n.get(e),s=o===void 0?a:Sq(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 Z(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,bq(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new Z(`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(lq)),a=n.net.filter(e=>!i.has(lq(e))),o=pq(Cq(xq(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new Z(`rewind: ${r.map(Tq).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 Z(`redo: nothing to redo`);let a=[...n,i],o=pq(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...hq(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(lq)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:Cq(n,t),future:Cq(i,t),...a!==void 0&&{savepoint:{at:Cq([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(lq(e))),below:Cq(a.below,t)}}}),new Z(`${r}: ${o.map(Tq).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):eK(t.file)}write(e,t,n){t.kind===`file`?tK(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){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||dq(n)>sq;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,fq(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${sq} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function dq(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 fq({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...hq(n,1,[])}:{past:e,future:t.slice(1),...hq(n,0,[])}}function pq(e){return e.slice(-50)}const mq=e=>e===Wk.member;function hq(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:gq(e.net,n),below:e.below}}}function gq(e,t){let n=new Map(e.map(e=>[lq(e),e]));for(let e of t){let t=n.get(lq(e));n.set(lq(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const _q=e=>e.map(e=>({...e,before:e.after,after:e.before}));function vq(e,t){let n=[...e.past,t],r=pq(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...hq(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...yq(e.future,a),...i.below]},n.length-r.length,t)}}function yq(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function bq(e,t){return{past:e.past.slice(0,-1),future:pq([...e.future,t]),...hq(e.savepoint,0,_q(t))}}function xq(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...yq(r,t.at-i.length),...t.below]}function Sq(e,t){if(mq(t.after)&&!mq(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!mq(t.after)&&mq(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function Cq(e,t){return e.map(e=>e.filter(e=>!t.has(lq(e)))).filter(e=>e.length>0)}function wq(e){return e.map(Tq).join(`, `)}function Tq(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function Eq(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 Dq(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(Eq))}function Oq(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(Eq)&&Dq(t.below)}function kq(e){if(typeof e!=`object`||!e)return!1;let t=e;return Dq(t.past)&&Dq(t.future)&&(t.savepoint===void 0||Oq(t.savepoint))}function Aq(e,t){let n=e=>e.kind===`file`||oq(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 jq(e,t){return{load:()=>{let n=new Map,r;try{r=s.readFileSync(e,`utf8`)}catch(e){let r=e.code;return r!==`ENOENT`&&t(`warn`,`settings-history read failed (${r}); starting empty`),n}try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(kq)){let r=new Set,i=nq(e,(e,n)=>t(`warn`,`settings-history load: dropped session key ${JSON.stringify(e)}: session id ${n}`));for(let[e,t]of i)n.set(e,Aq(t,r));return r.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...r].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),n}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),n},save:n=>{try{s.mkdirSync(E.dirname(e),{recursive:!0}),Dn(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 Mq=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function Nq(e){return{...Object.fromEntries(Mq.map(e=>[e,void 0])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const Pq=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Fq(e){let t=e=>({kind:`failed`,reason:e});if(!Pq(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!Pq(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!aM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${aM.join(` or `)}`)}return{kind:`ok`,value:e}}function Iq(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Lq=e=>wB(e,`doctor-marks.json`,{},Fq),Rq=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},zq=(e,t)=>e.includes(t)?e:[...e,t],Bq=e=>wB(e,`doctor-clicked-terminals.json`,[],Rq);var Vq=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const Hq=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},Uq=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),Wq=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=Uq(e,t);return r===void 0?n:r.projectDir},Gq=(e,t)=>Uq(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function Kq(e){let t=new Map;for(let n of e.split(`
|
|
187
|
-
`)){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*
|
|
188
|
-
`,1)[0]??``}function
|
|
189
|
-
`)){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
|
|
190
|
-
`)){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
|
|
191
|
-
`).length:0)}async getRemotesAsync(e){let t=
|
|
192
|
-
`)){let e=rY(n);e&&t.push(e)}return t}function aY(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function oY(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function sY(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Ho(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=aY(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,Uo(c,e=>iY(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 cY=class{values=X.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,X.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},lY=class{sessions;constructor(e,t,n,r,i=Pe,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new cY(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Mo(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=this.clock.monotonic(),o=await sY(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,A(this.clock,a)),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of oY(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Oo(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};const uY=[`first`,`period`,`change`,`request`,`supersede`];var dY=class{tallies=new Map;constructor(e=Pe){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,abandoned:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new pY(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(uY.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of uY)e[n]+=t.refreshes[n]??0;return e}};const fY={first:!0,period:!0,change:!0,request:!1,supersede:!0};var pY=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!fY[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}abandoned(e,t,n){this.tally.abandoned++,this.logger(`info`,`${this.tally.name} refresh ${e} by=${t} abandoned took=${n}ms`)}};function mY(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 hY=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new lY(void 0,mY,(e.ledger??new dY(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,t)}async refresh(e,t){return gY(await this.fold.read(e,t))}tokensOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:gY(t)}};function gY(e){return e.kind===`failed`?L(`context transcript: ${e.reason}`,e.failedAt):e.value===void 0?(k(`No main chain entries with usage data found`),I):F(e.value)}function _Y(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}function vY(e){let t=e.context_window;if(!t?.current_usage)return 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),a=_Y(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)}}function yY(e,t){let n=vY(t);if(n!==null)return F(n);if(e.kind!==`ok`)return e;let r=bY(t);return F({totalTokens:e.value,maxTokens:r,..._Y(e.value,r)})}function bY(e){return e.context_window?.context_window_size??2e5}const xY={messageCount:0,nonPrompts:0,recent:[]},SY=new Set([`turn`,`interrupt`,`claude-code`]);function CY(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!SY.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function wY(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 TY=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new lY(xY,CY,(e.ledger??new dY(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async refresh(e,t){return k(`Getting metrics from the transcript for session: ${e}`),EY(e,await this.fold.read(e,t))}foldOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:EY(e,t)}};function EY(e,t){return t.kind===`failed`?L(`metrics (${e}): ${t.reason}`,t.failedAt):F({lastResponseTime:wY(t.value.recent),messageCount:t.value.messageCount,nonPrompts:t.value.nonPrompts})}function DY(e,t){let n=t.cost;return n?e.kind===`ok`?F({...e.value,responseTime:n.total_api_duration_ms/1e3,sessionDuration:n.total_duration_ms/1e3,linesAdded:n.total_lines_added,linesRemoved:n.total_lines_removed}):e:I}function OY(e,t){return e.kind===`ok`?F({cost:t.cost?.total_cost_usd??e.value.calculatedCost,tokens:e.value.tokens}):e}function kY(e,t,n){return Ht({dir:e.project_dir,env:n===void 0?[]:[[Jo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const AY=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var jY=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const MY={reading:Oo(`unread`),fault:null};function NY(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function PY(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var FY=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.monotonic()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.clock.monotonic());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};const IY=()=>()=>{};var LY=class{entries=new Map;refreshes;closed=!1;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:[`first`,`period`,`change`,`supersede`]})}declare(e,t){if(this.closed)return LJ(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>FJ(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,NJ(n,`superseded`),this.abandon(n),n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())e(t.input)&&this.heard(t)}heard(e){e.holders>0&&this.refresh(e,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,abandoned:r,lastMs:i}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,abandoned:r,lastMs:i}}close(){this.closed=!0;for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:AJ(),holders:0,flight:null,changed:!1,superseding:0,revisit:RY(this.spec.every(t),this.spec.clock,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)}),unwatch:()=>{}};return this.entries.set(e,n),n.unwatch=this.spec.watch(t,()=>this.heard(n)),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n=new AbortController;e.flight=n;let r=this.spec.clock.monotonic();BY(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=A(this.spec.clock,r);if(n.signal.aborted){this.refreshes.abandoned(a,t,o);return}try{this.refreshes.recorded(a,t,i,o)}finally{this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input,e.holders)}): ${String(t)}`)})}store(e,t){e.flight=null;try{MJ(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0),this.evict()}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),this.abandon(e),e.unwatch(),e.revisit.dispose(),PJ(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function RY(e,t,n){if(e===null)return new zY(n.holdReturned);let r=new FY(n.period,t);return{landed:t=>r.landed(NY(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var zY=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function BY(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const VY=/\r\n|\r|\n/g,HY=e=>F(e.replace(VY,` `).trim());function UY(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(VY,` `))}}const WY=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},GY=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function KY(e,t,n,r){return{where:GY({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${Ze(i,` in ${n}`)}`,`read`)}}}function qY(e,t,n){return{where:GY({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await me(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function JY(e,t,n){switch(t.kind){case`shell`:return KY(e,t.command,t.cwd,n);case`file`:return qY(t.path,t.readMode,n)}}function YY(e){switch(e.kind){case`text`:return HY;case`regex`:return UY(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:WY(e)}}function XY(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var ZY=class{entries=new Map;releaseDelivery;constructor(e,t){this.watchers=e,this.fileEvents=t,this.releaseDelivery=t.subscribe(e=>this.noticed(e))}subscribe(e,t,n){let r=this.entries.get(e)??this.arm(e);return r.subscribers.set(t,n),n(this.faultOf(e,r)),()=>this.unsubscribe(e,t)}arm(e){let t=QY(e),n={bound:{derived:t,held:this.watchers.follow(null,t,t=>this.heard(e,n,t)).watch},subscribers:new Map};return this.entries.set(e,n),n}rederive(e,t){let n=QY(e),{watch:r}=this.watchers.follow(t.bound.held,n,n=>this.heard(e,t,n));t.bound={derived:n,held:r},this.report(e,t)}heard(e,t,n){let r=t.bound.derived.reached;if(this.rederive(e,t),!(n.kind!==`failed`&&!r&&!t.bound.derived.reached))for(let e of t.subscribers.keys())e()}report(e,t){let n=this.faultOf(e,t);for(let e of t.subscribers.values())e(n)}faultOf(e,t){return uV(`watch_file ${e}`,t.bound,zc(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const QY=e=>lV({named:[e],whole:[e]});var $Y=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Pe,n=e.ledger??new dY(t);this.watchMgr=new ZY(e.watchers??new gV({clock:e.clock}),e.fileEvents??Pc);let r=r=>new LY({name:`source.${r}`,scope:`daemon`,keyOf:e=>e.digest,fields:({digest:e,identity:t},n)=>`digest=${en(e)} where=${R(GY(t.read))} sharedBy=${n}`,read:async({identity:t},n)=>{let r=JY(e.launcher,t.read,n);return XY(await r.read(),YY(t.parse),r.where)},every:({identity:{refresh:e}})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:({digest:e,identity:t},n)=>{if(t.refresh.kind!==`watch_file`)return IY();let r=this.watchMgr.subscribe(t.refresh.path,n,t=>(0,X.runInAction)(()=>{t===null?this.faults.delete(e):this.faults.set(e,t)}));return()=>{r(),(0,X.runInAction)(()=>this.faults.delete(e))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let{digest:n}=t,r=this.byKind[t.identity.read.kind].declare(e,t);return{digest:n,current:()=>r.current(),fault:()=>this.faults.get(n)??null}}stats(){return{shell:this.byKind.shell.stats(),file:this.byKind.file.stats(),watches:this.watchMgr.size()}}close(){this.byKind.shell.close(),this.byKind.file.close(),this.watchMgr.dispose()}};function eX(e,t,n,r){return new Map([...n].map(([n,i])=>[n,r(n,()=>e.declare(t,i))]))}function tX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function nX(e){return{...Object.fromEntries(Tx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:nG(e.preset)}}}const rX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function iX(e){if(ko(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return ko(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const aX=10*1e3;function oX(e,t){if(!(t<60))return e*3600/t}function sX(e,t,n,r){let i=r-t;if(i<50||i>aX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function cX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=sX(t.input,t.atMs,n.input,n.atMs),i=sX(t.output,t.atMs,n.output,n.atMs),a=sX(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 lX(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>aX)continue;let o=sX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function uX(e){return kJ(e.termCols??120)}function dX(e,t){return Zo(Xo(e.claudeConfigDir,t))}function fX(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function pX(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${x(t)}`),a=`${e}: ${String(t)}`}n.set(e,A(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage()),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.refresh(o,r.transcript_path)),c(`metrics`,()=>i.metricsProvider.refresh(o,r.transcript_path)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(He(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(dX(a,i.home)))])}function mX(e,{plugins:t,runs:n}){let r=LJ(e);return{git:r,tmux:r,hostName:r,hostUser:r,today:r,sources:new Map([...t.keys()].map(e=>[e,r])),runs:new Map([...n.keys()].map(e=>[e,{digest:e,current:()=>r.current(),fault:()=>null}]))}}function hX({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,t.workspace?.project_dir]}function gX(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${x(t)}`),LJ(L(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...hX(n))),tmux:i===null?LJ(I):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r.plugins].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.hookData.session_id))])),runs:eX(e.sourceRuns,t,r.runs,(e,t)=>({digest:e,fault:()=>null,...o(`run ${en(e)}`,t)}))},faults:a}}function _X(e,t){let{deps:n}=e,r=e.hookData.session_id,i=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${x(t)}`),L(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:t.git.current(),usage:i(`session`,()=>n.usageStore.usageOf(r)),context:i(`context`,()=>n.contextProvider.tokensOf(r)),metrics:i(`metrics`,()=>n.metricsProvider.foldOf(r)),activity:i(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:t.tmux.current(),hostName:t.hostName.current(),hostUser:t.hostUser.current(),cache:i(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:i(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:i(`autocompact`,()=>n.autoCompact.stored(dX(e.hints,n.home))),sources:new Map([...t.sources].map(([e,t])=>[e,t.current()])),runs:new Map([...t.runs].map(([e,t])=>[e,{reading:t.current(),fault:t.fault()}]))},today:i(`today`,()=>vX(t.today,n.usageStore,r)),faults:AY.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{kind:`lane`,lane:e,reason:t.reason}]})}}function vX(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function yX({builtins:e,sources:t,runs:n},r){return[e.git,e.tmux,e.hostName,e.hostUser,...Object.values(t),...[...r].map(e=>(n[e.digest]??MY).reading)].some(bX)}const bX=e=>e.kind===`pending`&&e.why===`unread`;async function xX(e,t,n,r,i,a){await pX(e,t,n);try{await(0,X.when)(()=>!yX(r(),i()),{signal:a})}catch(e){if(!a.aborted)throw e}}function SX(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?Oo(t.why):void 0}const CX=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function wX(e,t,n){let{hookData:r,hints:i}=t,a=r.session_id,{effective:o,configFacts:s}=n,{configPath:c,...l}=s,u=e.builtins,d={usage:OY(CX(u.session),r),context:yY(CX(u.context),r),metrics:DY(CX(u.metrics),r),activity:CX(u.activity),cache:CX(u.cache),speed:CX(u.speed),autoCompact:CX(u.autocompact),git:CX(u.git),pr:CX(u.pr),tmux:CX(u.tmux),hostName:CX(u.hostName),hostUser:CX(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return Oo(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},p=e=>e.kind===`ok`?e.value:void 0,m=i.tmux??null,h=d.git.kind===`pending`?Oo(d.git.why):d.git.kind===`ok`?IX(d.git.value,d.pr,Oo):void 0,g=d.tmux.kind===`pending`?Oo(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?Oo(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?Oo(d.hostUser.why):p(d.hostUser),y=SX(d.context)??jX(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=SX(d.usage,d.metrics)??OX(p(d.usage)?.cost,p(d.metrics)?.sessionDuration),C=f(d.speed,kX),w=f(d.usage,e=>PX({cost:e.cost,tokens:e.tokens})),T=f(d.metrics,e=>PX({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),ee=f(d.activity,MX),te=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),E=f(d.cache,e=>({expiresAt:e})),ne=FX(t.home),D=r.workspace?{...r.workspace,current_dir:FX(r.workspace.current_dir)??``,project_dir:FX(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>FX(e)??e)}:r.workspace;return{...r,...D!==void 0&&{workspace:D},...ne!==void 0&&{home:ne},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:FX(r.location.main)??``}},...m!==null&&{tmux:{pane:m.pane,...g!==void 0&&{session:g}}},host:{..._!==void 0&&{name:_},...v!==void 0&&{user:v},...i.ssh!==void 0&&{ssh:i.ssh}},...nX(o),history:n.history,navigation:{back:n.back},term:{cols:uX(i)},...l,...c!==null&&{configPath:c},resumeCommand:kY(D,a,i.claudeConfigDir),...w!==void 0&&{session:w},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...E!==void 0&&{cache:E},...te!==void 0&&{context:te},...T!==void 0&&{metrics:T},...ee!==void 0&&{activity:ee},...y!==void 0&&{autocompact:y},...DX(n.sources,t=>{let n=CX(TX(e,t));return n.kind===`pending`?Oo(n.why):n})}}const TX=(e,t)=>e.sources[t]??Oo(`unread`);function EX(e,t,n){let r=[...e.map(e=>[e,TX(n,e)]),...[...t].map(([e,t])=>[e,t===void 0?MY.reading:(n.runs[t.digest]??MY).reading])];return{sources:String(r.length),sourcesPending:r.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function DX(e,t){let n=Object.fromEntries(_k.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function OX(e,t){let n=e!=null&&t!=null?oX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function kX(e){let t=cX(e),n=lX(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function AX(e,t){if(e.kind===`pending`)return Oo(e.why);if(e.kind!==`ok`)return;let n=HJ(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}function jX(e,t){switch(e.kind){case`pending`:return Oo(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return FN(e.value,t)}}function MX(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=NX(e.running),i=NX(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 NX(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function PX(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 FX(e){return e===void 0||e.length===0||E.sep!==`\\`?e:e.replace(/\\/g,`/`)}function IX(e,t,n){let r=e=>e.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=r(Jq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Yq(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts,...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const LX=(e,t)=>[...e].some(e=>e===t||e.startsWith(`${t}.`)),RX={pullRequests:e=>Object.keys(rX).some(t=>e.has(`git.${t}`)),rateLimits:e=>LX(e,`block`)||LX(e,`weekly`)};function zX(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]),...Object.values(n.partials??{})]:[]}function BX(e,t){let n=kU(e),r=new Map(XR(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=DU(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function VX(e,t){let n=new Map;for(let r of Wy(vS(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=>tb(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,BX(e,[...zX(e,t),...n.get(t)])])),a=e=>r.filter(t=>RX[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
|
|
185
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=MV(e,`root`,t.root)),t.insert!==void 0&&(a.insert=PV(e,t.insert,i)),t.actions!==void 0&&(a.actions=EL(e,t.actions,r)),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:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=iH(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=gC(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=oH(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=bC(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=TL(e,t.helpers)),t.plugins!==void 0&&(a.plugins=HW(e,t.plugins)),HV(e,a),$V(e,a),Jk(e,a),Nk(e,a,P,`the global settings menu`),Pk(e,a,n),a}const VW=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function HW(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 ${bb(t)}`,line:q(e.source,[`plugins`])})}const UW={},WW=AN(`commands.`),GW=IN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),KW=wN(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),qW=`{{ ${dA} }}`,JW={min:0,max:100,step:5},YW={warnAt:{label:`warning at %`,domain:JW,default:50},errorAt:{label:`error at %`,domain:{...JW,atLeast:`warnAt`},default:80}};function XW(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:JW,default:80}}}const ZW={globals:{palette:`tokyo-night`},variables:{...WW.variables,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:`? `},"glyph.worktree":{kind:`literal`,value:`⊫`},...KW.variables,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.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"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:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"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},"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 main checkout's path, shortened fish-style — `~` under home — plus the subpath and, in a linked worktree, the worktree's name. Click to copy the full path.",template:`{{ $dir := ternary .location.main .current_dir (ne .location.main "") }}{{ if and (ne .home "") (or (eq .home $dir) (hasPrefix (printf "%s/" .home) $dir)) }}{{ $dir = printf "~%s" (trimPrefix .home $dir) }}{{ end }}{{ $text := printf "%s%s" (abbreviatePath $dir) .location.subpath }}{{ if ne .location.worktree "" }}{{ $text = printf "%s (%s %s)" $text .glyph.worktree .location.worktree }}{{ end }}{{ action "copyDir" $text }}`,fg:qW},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 ne .git.branch "" }}{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}{{ end }}{{ if or .location.noRepo ${KW.armed} }}{{ if ne .git.branch "" }} {{ end }}${KW.template}{{ end }}`,fg:qW,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:vN(``).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:WW.template,when:WW.when},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:XW(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:XW(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:YW,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:YW,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) ${Ov} }}`,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 }}`},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:GW.template,bg:GW.bg,when:GW.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:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...vN(``).actions,...WW.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...KW.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...GW.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:UW,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:`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:`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:`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 }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Ov} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${dA}) 2 (readableOn (color "accent") (bgOf) ${Ov})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Ov}) .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:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ 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 .)) }}`}},QW=new Set([ZW.globals.palette,...Object.keys(ZW.themeDefaults),...Object.values(ZW.segments).map(e=>e.palette)].filter(e=>e!==void 0)),$W=XF(IW(`<default>`,JSON.stringify(ZW),QW),ZW),eG=mS($W.presets);function tG(e){return eG.includes(e)}const nG=Object.freeze({});function rG(e,t){return e.kind===`decided`?t[e.name]??nG:nG}function iG(e,t){return{...e,...Object.fromEntries(Tx.map(n=>[n,e[n]??t[n]]))}}const aG=(e,t)=>Yb(n=>{let{setting:r,on:i,inTmux:a}=Hb[n].switch;return e[r]===i&&(t||!a)});function oG(e,t,n,r){let i=Ex(e);return ey(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function sG(e,t){return hS(t(`preset`),e.globals.preset,e.presets)}function cG(e,t,n){let r=sG(e,t),i=bS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Jx(a.palette,t(`theme`),i.palette),s=iG(i,rG(o,e.themeDefaults));return{...Object.fromEntries(wx.map(e=>[e,oG(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:fy(a.style,t(`style`),s.style,e.styles),effect:Sy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function lG(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?jy:My;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const uG=Object.entries(jx),dG=new Set(Nx.map(e=>e.sessionKey)),fG=()=>!1;function pG(e,t){return cG(e,e=>dG.has(e)?t(e):null,fG)}const mG=[`preset`,`theme`];function hG(e,t,n){let r=new Set(mG.slice(0,n).map(e=>jx[e].sessionKey));return cG(e,e=>r.has(e)?t(e):null,fG)}function gG(e,t){let n=Array.from({length:mG.length+1},(n,r)=>hG(e,t,r));return e=>{let t=mG.indexOf(e);return n[t===-1?mG.length:t]}}function _G(e,t,n,r){return e.flatMap(([e,i])=>{let a=lG(t,e);return a===null||a===lG(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function vG(e,t,n){return lG(pG(e,t),n)}function yG(e,t){let n=pG(e,t);return _G(uG,n,gG(e,t),t=>bG(e,n.preset,t.configKey))}function bG(e,t,n){return n in(gS(e.presets,t).globals??{})?PC(t,n):n}function xG(e,t,n){let r=hS(t(jx.preset.sessionKey),e.globals.preset,e.presets),i=FC(n);return{key:i?.scope===`globals`?bG(e,r,i.field):n,globals:bS(e,r)}}function SG(e,t){let{preset:n}=pG(e,t);return TG(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:ub(a,s);return c===void 0||lb(c)===lb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function CG(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return mS(e.presets).flatMap(n=>{let i=TG(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 sb(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:ub(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const wG=new WeakMap;function TG(e,t){let n=wG.get(e)??new Map;wG.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Uy(_S(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=ab(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 EG(e,t){let n=pG(e,t);return{from:n.preset,globals:gS(e.presets,n.preset).globals??{},picks:_G(uG.filter(([e])=>e!==`preset`),n,gG(e,t),e=>e.configKey),placements:SG(e,t)}}function DG(e,t){return cG({...e,globals:{palette:t},presets:{}},()=>null,fG)}function OG(e,t){let n=pG(e,t),r=lG(n,`theme`);if(r===null)return{kind:`rule`};let i=DG(e,r),a=bS(e,n.preset),o=Object.fromEntries(Tx.map(e=>[e,lG(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Tx.some(e=>o[e]!==lG(i,e))}}function kG(e){return{sessionKeys:Nx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...fC(e)?eG.map(t=>PC(t,e)):[],...NC(e)?ty().map(t=>MC(t,e)):[]]}}function AG(e){return new Set(Nx.map(e=>e.configKey).filter(t=>kG(t).fileKeys.some(t=>NG(e,MG(t)))))}function jG(e,t,n){let r=yG(e,n),i=new Set(r.map(e=>e.configKey)),a=Rx(e=>i.has(jx[e].configKey)||t.has(jx[e].configKey)),o=OG(e,n);return{unsaved:r.length+SG(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function MG(e){let t=FC(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return IC(t)}function NG(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&NG(e[n],r)}function PG(e,t,n){let r=zx.get(n);if(r!==void 0)return vG(e,t,r);for(let[,t]of tb(e))if(t.key===n)return t.default??null;return null}function FG(e,t){let n=EC(e).get(t);return n===void 0?null:String(n)}const IG={inside:()=>[],defaultOf:()=>gi,menus:[]},LG=e=>`${e.key}\0${e.member}`;function RG(e){let t=new Map,n=n=>{let r=`${n.name}\0${zy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:XV(a,zy(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(LG(e))??new Map;n.set(LG(t),t),o.set(LG(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(LG(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of mS(e.presets))d(_S(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Ai(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(LG(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(LG(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(LG(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const zG=new WeakMap;function BG(e){let t=zG.get(e);if(t!==void 0)return t;let n=RG(e);return zG.set(e,n),n}function VG(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function HG(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function UG(e,t,n){let r=(r,i,a)=>{let o=VG(t(r),t=>e.get(r,t),i);(0,X.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const WG=`render-origin`,GG=`client-hints`,KG=`config-override`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},qG=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},JG=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function YG(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}const XG=new Set([`1`,`true`]),ZG=new Set([`0`,`false`,``]);function QG(e,t){let n=CK(e),r=n.scope===`segment-palette`?`string`:Ox(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(XG.has(t))return`true`;if(ZG.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function $G(e){try{return s.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function eK(e,t,n){try{if(t===null){s.rmSync(On(e),{force:!0});return}Dn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function tK(e){return/^\s*$/.test(e)?null:Ua(e)}function nK(e,t){return e!==null&&Ga(e,t)!==void 0}function rK(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(rK),...i}}return e}function iK(e){if(!$x(e))return rK(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,rK(t)])),...n}}const aK=ZW,oK=aK.segments,sK=aK.presets,cK=aK.root;function lK(e,t,n,r){if(!nK(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function uK(e,t){let n=IC(t);return t.scope===`segment-palette`&&lK(e,[`segments`,t.segment],oK[t.segment],n.join(`.`)),n}function dK(e){return Ua(Qa(e))}function fK(){return Object.entries(cK.rows).map(([e,t])=>{let n=rK(t);return{path:[`root`],fragment:dK({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function pK(e,t){let n=e===null?void 0:Ga(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function mK(e,t){if(t===void 0)return null;let n=iK(t);return{path:e,fragment:dK(n),unit:{path:e,value:n}}}function hK(e,t){let n=[`presets`,t],r=[...n,`root`],i=sK[t];lK(e,n,i,r.join(`.`));let a=pK(e,r)??mK(r,i?.root);return a!==null&&yo(a.fragment)?a:null}function gK(e,t){let n=vo(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 _K(e,t){return[...fK(),pK(e,[`root`]),hK(e,t)].filter(e=>e!==null).reduce(gK,new Map)}function vK(e,t,n){for(let{node:r,...i}of _K(e,t).values())if(xo(r,n))return i;throw new Z(`${yK(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 yK(e,t){return hK(e,t)?.path??[`root`]}function bK(e,t){return t.scope===`preset-root`?yK(e,t.preset):IC(t)}function xK(e,{unit:t}){return t===null?e:fo(e,t.path,Qa(t.value),Xa)}function SK(e){let t=FC(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function CK(e){let t=SK(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function wK(e,t,n,r,i){let a=FK(t,r),o,s=()=>(o??={chain:kK(t,n)}).chain;IK(t,s,a),i(t,s,a),eK(t.path,r,e.logger),e.record(t.path,n,r)}function TK(e,t,n){let r=OK(e,t(),n);if(r.length>0)throw new Z(`refused: ${e.above.map(e=>e.path).join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const EK=()=>{};function DK(e,t){try{return t()}catch(t){throw!(t instanceof Z)||e.above.length===0?t:new Z(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function OK(e,t,n){if(t===null)return[];let r=new Set(NK(MK(t),MK(n)));return NK(jK(e,t),jK(e,n)).filter(e=>!r.has(e))}function kK(e,t){try{return AK(e,t)}catch(e){if(e instanceof fb)return null;throw e}}function AK(e,t){return DW(e.locs,t===null?e.above:[mB(e.path),...e.above],$W,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:s.readFileSync(n,`utf8`))}function jK(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function MK(e){return e.layers.at(-1)?.config??e.base}function NK(e,t,n=``){return!PK(e)||!PK(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>NK(e[r],t[r],n===``?r:`${n}.${r}`))}function PK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function FK(e,t){try{return AK(e,t)}catch(e){throw e instanceof fb?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function IK(e,t,n){if(n.dropped.length===0)return;let r=t();if(r===null)return;let i=e=>e.dropped.flatMap(e=>e.issues.map(t=>({file:e.file,issue:t}))),a=new Set(i(r).map(({file:e,issue:t})=>`${e}\0${t.message}`)),o=i(n).filter(({file:e,issue:t})=>!a.has(`${e}\0${t.message}`));if(o.length>0)throw new Z(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new fb(e,[t]).message).join(`
|
|
186
|
+
`)}`)}function LK(e,t){let n=CK(t),r=tK($G(e)??``),i=r===null?void 0:Ga(r,IC(n));return i!==void 0&&`value`in i?i.value:void 0}function RK(e,t,n){zK(e,t,n,[])}function zK(e,t,n,r){let i=$G(t.path),a=n.reduce((e,[t,n])=>fo(e,uK(tK(e),CK(t)),QG(t,n),Xa),i??``);wK(e,t,i,DK(t,()=>BK(a,t.path,r,e=>e)),TK)}function BK(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=vK(tK(s),n,i),l=To(xK(s,c),c.path,i,a,Qa(o));if(l===null)throw new Z(`${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 VK(e,t,n){let r=tK(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of _K(r,t)){if(!xo(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qa(e,c):Qa(s.value);if(a!==`#`)return fo(e,[...i,`rows`,a],l,Xa);if(hK(r,t)!==null)throw new Z(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return fo(e,i,l,Xa)}return e}function HK(e,t){return mo(e,t,t[0]===`presets`&&t.length>2&&!tG(t[1])?2:0)}function UK(e,t,n){let r=n.map(SK),i=$G(t.path);if(i===null)return;let a=r.reduce((e,t)=>HK(e,bK(tK(e),t)),i);a!==i&&wK(e,t,i,a,EK)}function WK(e){let t=e===null?void 0:Ga(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function GK(e,t){let n=new Set([...eG,...WK(e),...t.above.flatMap(e=>Object.keys(Ia.default.parse(s.readFileSync(e.path,`utf8`)).presets??{}))].map(DS));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(DS(e)))}function KK(e,t,n,r,i,a){let o=$G(t.path),s=tK(o??``),c=GK(s,t),l=[`presets`,c],u=DK(t,()=>hK(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qa(o??``,u.fragment):Qa(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Qa(r)]]],f=i.map(([e,t])=>{let n=PC(c,e);return[uK(s,CK(n)),QG(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>fo(e,t,n,Xa),fo(o??``,l,`{}`,Xa));return wK(e,t,o,DK(t,()=>BK(p,t.path,a.map(e=>({...e,preset:c})),VK)),TK),c}function qK(e,t,n,r){let i=$G(t.path);wK(e,t,i,fo(i??``,[`themeDefaults`,n],Qa(r),Xa),TK)}function JK(e,t,n){if(tG(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=$G(t.path),a=tK(i??``);if(i===null||a===null||Ga(a,r)===void 0)throw new Z(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ga(a,[`globals`,`preset`]);wK(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>HK(e,t),i),EK)}function YK(e,t,n,r){let i=SK(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=$G(t.path),o=r.op===`remove`?r.target:r.anchor,s=DK(t,()=>vK(tK(a??``),i.preset,o)),c=xK(a??``,s),{after:l,placed:u}=XK(c,s.path,r,()=>{let e=FK(t,c).config;return mS(e.presets).map(t=>_S(e,t).node)});if(l===null)throw new Z(`${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 wK(e,t,a,l,TK),u}function XK(e,t,n,r){switch(n.op){case`remove`:return{after:Co(e,t,n.target),placed:null};case`insert`:{let i=Qte(n.segment,n.anchor,r());return{after:wo(e,t,i,n.anchor,n.relation),placed:i}}}}function ZK(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 QK={load:()=>new Map,save:()=>{},flush:()=>{}};var $K=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e=QK,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Array.from(this.storage.load(),([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,X.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,X.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,X.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()}close(){this.flush(),this.storage=QK}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 eq(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function tq(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=eq(r);e.ok?n.set(e.id,i):t(r,e.problem)}return n}function nq(e){let t=eq(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const rq={load:()=>new Map,save:()=>{}},iq=new Set(Nx.map(e=>e.sessionKey)),aq=e=>iq.has(e)||e.startsWith(Hk),oq=8*1024*1024,sq={past:[],future:[]},cq=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var lq=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=rq){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(n.load())}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??sq;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??sq}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(cq(r));i.set(cq(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:ZK(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!aq(i)&&i!==`edit.mode`)){if(i===`edit.mode`){let t=r.get(e);r.set(e,{before:t===void 0?a:t.before,after:o});return}n(e,{kind:`session`,key:i,before:a,after:o})}}),file:(e,t,r,i)=>n(e,{kind:`file`,file:t,before:r,after:i}),wrote:()=>{t=!0},written:()=>t,commit:()=>{let t=new Map(e),n=new Map(r);e.clear(),r.clear();for(let e of new Set([...t.keys(),...n.keys()])){let r=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=r.length===0?i:_q(i,r),o=n.get(e),s=o===void 0?a:xq(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 Z(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,yq(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new Z(`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(cq)),a=n.net.filter(e=>!i.has(cq(e))),o=fq(Sq(bq(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new Z(`rewind: ${r.map(wq).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 Z(`redo: nothing to redo`);let a=[...n,i],o=fq(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...mq(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(cq)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:Sq(n,t),future:Sq(i,t),...a!==void 0&&{savepoint:{at:Sq([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(cq(e))),below:Sq(a.below,t)}}}),new Z(`${r}: ${o.map(wq).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):$G(t.file)}write(e,t,n){t.kind===`file`?eK(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){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||uq(n)>oq;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,dq(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${oq} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function uq(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 dq({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...mq(n,1,[])}:{past:e,future:t.slice(1),...mq(n,0,[])}}function fq(e){return e.slice(-50)}const pq=e=>e===Wk.member;function mq(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:hq(e.net,n),below:e.below}}}function hq(e,t){let n=new Map(e.map(e=>[cq(e),e]));for(let e of t){let t=n.get(cq(e));n.set(cq(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const gq=e=>e.map(e=>({...e,before:e.after,after:e.before}));function _q(e,t){let n=[...e.past,t],r=fq(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...mq(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...vq(e.future,a),...i.below]},n.length-r.length,t)}}function vq(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function yq(e,t){return{past:e.past.slice(0,-1),future:fq([...e.future,t]),...mq(e.savepoint,0,gq(t))}}function bq(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...vq(r,t.at-i.length),...t.below]}function xq(e,t){if(pq(t.after)&&!pq(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!pq(t.after)&&pq(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function Sq(e,t){return e.map(e=>e.filter(e=>!t.has(cq(e)))).filter(e=>e.length>0)}function Cq(e){return e.map(wq).join(`, `)}function wq(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function Tq(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 Eq(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(Tq))}function Dq(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(Tq)&&Eq(t.below)}function Oq(e){if(typeof e!=`object`||!e)return!1;let t=e;return Eq(t.past)&&Eq(t.future)&&(t.savepoint===void 0||Dq(t.savepoint))}function kq(e,t){let n=e=>e.kind===`file`||aq(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 Aq(e,t){return{load:()=>{let n=new Map,r;try{r=s.readFileSync(e,`utf8`)}catch(e){let r=e.code;return r!==`ENOENT`&&t(`warn`,`settings-history read failed (${r}); starting empty`),n}try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(Oq)){let r=new Set,i=tq(e,(e,n)=>t(`warn`,`settings-history load: dropped session key ${JSON.stringify(e)}: session id ${n}`));for(let[e,t]of i)n.set(e,kq(t,r));return r.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...r].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),n}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),n},save:n=>{try{s.mkdirSync(E.dirname(e),{recursive:!0}),Dn(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 jq=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function Mq(e){return{...Object.fromEntries(jq.map(e=>[e,void 0])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const Nq=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Pq(e){let t=e=>({kind:`failed`,reason:e});if(!Nq(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!Nq(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!aM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${aM.join(` or `)}`)}return{kind:`ok`,value:e}}function Fq(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Iq=e=>CB(e,`doctor-marks.json`,{},Pq),Lq=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},Rq=(e,t)=>e.includes(t)?e:[...e,t],zq=e=>CB(e,`doctor-clicked-terminals.json`,[],Lq);var Bq=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const Vq=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},Hq=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),Uq=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=Hq(e,t);return r===void 0?n:r.projectDir},Wq=(e,t)=>Hq(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function Gq(e){let t=new Map;for(let n of e.split(`
|
|
187
|
+
`)){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*Kq(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)}function qq(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function Jq(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const Yq={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},Xq={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Zq(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const Qq={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function $q(e){return Object.keys(Qq).flatMap(t=>{let n=e[t];return n.kind===`failed`?[`git.${Qq[t]}: ${n.reason}`]:[]})}function eJ(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(tJ(e,t),`read`)}function tJ(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??nJ(t.stderr)].filter(Boolean).join(`, `)}`}function nJ(e){return e.trim().split(`
|
|
188
|
+
`,1)[0]??``}function rJ(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function iJ(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const aJ={github:`gh`,gitlab:`glab`};function oJ(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const sJ=/^[A-Za-z]:[\\/]/;function cJ(e){let t=e.trim();if(sJ.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 lJ(e){return cJ(e)?.host||null}function uJ(e){let t=lJ(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const dJ=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function fJ(e){let t=eJ(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?pJ(t.value):[]}}function pJ(e){let t=new Map;for(let n of e.split(`
|
|
189
|
+
`)){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 mJ(e){return e.urls.find(e=>yJ(e)!==null)??e.urls[0]??null}function hJ(e){return e.find(e=>e.name===`origin`)??e[0]??null}function gJ(e){let t=hJ(e);return t?mJ(t):null}function _J(e){let t=hJ(e);return t?t.urls.find(e=>uJ(e)!==null)??mJ(t):null}function vJ(e){let t=(cJ(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function yJ(e){let t=cJ(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 bJ(e){let t=gJ(e);return t===null?null:yJ(t)}function xJ(e,t,n,r){return t.ok?r(t.stdout):oJ(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??nJ(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function SJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function CJ(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
190
|
+
`)){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 wJ(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!SJ(t))return L(`gh pr view: JSON is not an object`,`parse`);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`,`parse`);let o=Zq(`gh pr view`,Yq,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function TJ(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!SJ(t))return L(`glab mr view: JSON is not an object`,`parse`);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`,`parse`);let o=Zq(`glab mr view`,Xq,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function EJ(e){try{let t=s.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var DJ=class{constructor(e){this.launcher=e}isGitRepo(e){return Uz(e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=Wz(e);return t===void 0?I:F(t)}async getGitInfo(e,t){try{return await this.computeGitInfo(e,t)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`,`read`)}}async computeGitInfo(e,t){let n;if(this.isWorktree(e))n=e;else if(t&&this.isGitRepo(t))n=t;else if(this.isGitRepo(e))n=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;n=t.value}let r=await this.getCoreAsync(n);if(r.kind!==`ok`)return r;let i=await this.committedAt(n,r.value.oid),a=await this.getRemotesAsync(n);return F({branch:r.value.branch,status:r.value.status,aheadBehind:r.value.aheadBehind,head:r.value.oid,workingTree:r.value.workingTree,sha:rJ(r.value.oid,e=>e.slice(0,7)),upstream:r.value.upstream,committedAt:i,stashCount:this.getStashCount(n),repoName:rJ(a,e=>this.repoNameFrom(e,n)),repoUrl:rJ(a,bJ),operation:this.getOngoingOperation(n)})}resolveGitDir(e){return Eo(Yz(e),E.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return s.existsSync(E.join(t,`MERGE_HEAD`))?F(`MERGE`):s.existsSync(E.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):s.existsSync(E.join(t,`REVERT_HEAD`))?F(`REVERT`):s.existsSync(E.join(t,`BISECT_LOG`))?F(`BISECT`):s.existsSync(E.join(t,`rebase-merge`))||s.existsSync(E.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(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.readCommitTimestamp(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 readCommitTimestamp(e,t){let n=iJ(eJ(`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);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`,`parse`):F(r)}resolveCommonGitDir(e){return Eo(Xz(e),e)}getStashCount(e){let t=E.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=s.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return F(r?r.split(`
|
|
191
|
+
`).length:0)}async getRemotesAsync(e){let t=EJ(E.join(this.resolveCommonGitDir(this.resolveGitDir(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 fJ(await this.execGitAsync(dJ,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=gJ(e);return(n===null?null:vJ(n))??E.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=_J(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=uJ(t);return n===`github`?xJ(`gh pr view`,await this.execForgeAsync(aJ.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,wJ):n===`gitlab`?xJ(`glab mr view`,await this.execForgeAsync(aJ.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,TJ):I}isWorktree(e){try{let t=E.join(e,`.git`);return!!(s.existsSync(t)&&s.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){k(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=eJ(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(CJ(t.value)):t}};function OJ(e){return Math.max(1,e-2)}function kJ(){return X.observable.box(AJ(`unread`),{deep:!1})}function AJ(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function jJ(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,X.compareStructural)(n,t)||((0,X.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function MJ(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,X.runInAction)(()=>e.reading.set({...n,why:t})):(0,X.runInAction)(()=>e.reading.set(AJ(t)))}function NJ(e,t){e.reading.get().kind===`pending`&&jJ(e,t)}function PJ(e){return e.reading.get()}function FJ(e,t,n,r){let i=new AbortController,a=r(Math.max(0,t),()=>i.abort());return new Promise((t,r)=>{i.signal.addEventListener(`abort`,()=>t(`deadline`)),e(i.signal).then(()=>t(`answered`),e=>i.signal.aborted?n(e):r(e))}).finally(()=>{a(),i.abort()})}function IJ(e){return{current:()=>e}}const LJ={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function RJ(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function zJ(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function BJ(e,t,n){return{[zJ(He(e))]:{...LJ,cost:t,input:n}}}function VJ(e,t){let n=zJ(He(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return I;let a={...LJ};return r!==void 0&&RJ(a,r),i!==void 0&&RJ(a,i),F({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}const HJ=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function UJ(e){if(typeof e==`string`)return HJ.exec(e)?.[1]}function WJ(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 GJ(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 KJ(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=WJ(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`?UJ(GJ(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 qJ(e,t){return e===void 0?[ie(t,`.config`,`claude`),ie(t,`.claude`)].filter(e=>u(e)):[e]}async function JJ(e){let t=[];for(let n of e){let e=ie(n,`projects`),r=await YJ(Io(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(ie(e,n.name))}return t}async function YJ(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function XJ(e,t,n){let r=[],i=[],a=ie(t,e,`subagents`);try{let t=(await Io(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=ie(a,o);if(n?.has(t)){r.push(t);continue}let s=await Ho(t,void 0,void 0);if(s.kind!==`ok`){k(`Failed to check agent file ${t}`);continue}i=iY(i,t,s.value);let c=tY(Uo(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){k(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function ZJ(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if($J(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=GJ(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||QJ.test(r)?`claude-code`:`prompt`}const QJ=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function $J(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function eY(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=ZJ(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:KJ(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 tY(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 nY(e){let t=tY(e);if(t.kind===`unparsed`)return k(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return eY(t.value)}catch(e){return k(`Failed to project JSONL line: ${e}`),null}}function rY(e){let t=[];for(let n of e.split(`
|
|
192
|
+
`)){let e=nY(n);e&&t.push(e)}return t}function iY(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function aY(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function oY(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Ho(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=iY(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,Uo(c,e=>rY(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 sY=class{values=X.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,X.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},cY=class{sessions;constructor(e,t,n,r,i=Pe,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new sY(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Mo(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=this.clock.monotonic(),o=await oY(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,A(this.clock,a)),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of aY(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Oo(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};const lY=[`first`,`period`,`change`,`request`,`supersede`];var uY=class{tallies=new Map;constructor(e=Pe){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,abandoned:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new fY(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(lY.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of lY)e[n]+=t.refreshes[n]??0;return e}};const dY={first:!0,period:!0,change:!0,request:!1,supersede:!0};var fY=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!dY[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}abandoned(e,t,n){this.tally.abandoned++,this.logger(`info`,`${this.tally.name} refresh ${e} by=${t} abandoned took=${n}ms`)}};function pY(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 mY=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new cY(void 0,pY,(e.ledger??new uY(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,t)}async refresh(e,t){return hY(await this.fold.read(e,t))}tokensOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:hY(t)}};function hY(e){return e.kind===`failed`?L(`context transcript: ${e.reason}`,e.failedAt):e.value===void 0?(k(`No main chain entries with usage data found`),I):F(e.value)}function gY(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}function _Y(e){let t=e.context_window;if(!t?.current_usage)return 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),a=gY(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)}}function vY(e,t){let n=_Y(t);if(n!==null)return F(n);if(e.kind!==`ok`)return e;let r=yY(t);return F({totalTokens:e.value,maxTokens:r,...gY(e.value,r)})}function yY(e){return e.context_window?.context_window_size??2e5}const bY={messageCount:0,nonPrompts:0,recent:[]},xY=new Set([`turn`,`interrupt`,`claude-code`]);function SY(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!xY.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function CY(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 wY=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new cY(bY,SY,(e.ledger??new uY(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async refresh(e,t){return k(`Getting metrics from the transcript for session: ${e}`),TY(e,await this.fold.read(e,t))}foldOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:TY(e,t)}};function TY(e,t){return t.kind===`failed`?L(`metrics (${e}): ${t.reason}`,t.failedAt):F({lastResponseTime:CY(t.value.recent),messageCount:t.value.messageCount,nonPrompts:t.value.nonPrompts})}function EY(e,t){let n=t.cost;return n?e.kind===`ok`?F({...e.value,responseTime:n.total_api_duration_ms/1e3,sessionDuration:n.total_duration_ms/1e3,linesAdded:n.total_lines_added,linesRemoved:n.total_lines_removed}):e:I}function DY(e,t){return e.kind===`ok`?F({cost:t.cost?.total_cost_usd??e.value.calculatedCost,tokens:e.value.tokens}):e}function OY(e,t,n){return Ht({dir:e.project_dir,env:n===void 0?[]:[[Jo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const kY=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var AY=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const jY={reading:Oo(`unread`),fault:null};function MY(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function NY(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var PY=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.monotonic()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.clock.monotonic());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};const FY=()=>()=>{};var IY=class{entries=new Map;refreshes;closed=!1;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:[`first`,`period`,`change`,`supersede`]})}declare(e,t){if(this.closed)return IJ(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>PJ(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,MJ(n,`superseded`),this.abandon(n),n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())e(t.input)&&this.heard(t)}heard(e){e.holders>0&&this.refresh(e,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,abandoned:r,lastMs:i}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,abandoned:r,lastMs:i}}close(){this.closed=!0;for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:kJ(),holders:0,flight:null,changed:!1,superseding:0,revisit:LY(this.spec.every(t),this.spec.clock,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)}),unwatch:()=>{}};return this.entries.set(e,n),n.unwatch=this.spec.watch(t,()=>this.heard(n)),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n=new AbortController;e.flight=n;let r=this.spec.clock.monotonic();zY(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=A(this.spec.clock,r);if(n.signal.aborted){this.refreshes.abandoned(a,t,o);return}try{this.refreshes.recorded(a,t,i,o)}finally{this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input,e.holders)}): ${String(t)}`)})}store(e,t){e.flight=null;try{jJ(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0),this.evict()}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),this.abandon(e),e.unwatch(),e.revisit.dispose(),NJ(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function LY(e,t,n){if(e===null)return new RY(n.holdReturned);let r=new PY(n.period,t);return{landed:t=>r.landed(MY(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var RY=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function zY(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const BY=/\r\n|\r|\n/g,VY=e=>F(e.replace(BY,` `).trim());function HY(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(BY,` `))}}const UY=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},WY=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function GY(e,t,n,r){return{where:WY({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${Ze(i,` in ${n}`)}`,`read`)}}}function KY(e,t,n){return{where:WY({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await me(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function qY(e,t,n){switch(t.kind){case`shell`:return GY(e,t.command,t.cwd,n);case`file`:return KY(t.path,t.readMode,n)}}function JY(e){switch(e.kind){case`text`:return VY;case`regex`:return HY(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:UY(e)}}function YY(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var XY=class{entries=new Map;releaseDelivery;constructor(e,t){this.watchers=e,this.fileEvents=t,this.releaseDelivery=t.subscribe(e=>this.noticed(e))}subscribe(e,t,n){let r=this.entries.get(e)??this.arm(e);return r.subscribers.set(t,n),n(this.faultOf(e,r)),()=>this.unsubscribe(e,t)}arm(e){let t=ZY(e),n={bound:{derived:t,held:this.watchers.follow(null,t,t=>this.heard(e,n,t)).watch},subscribers:new Map};return this.entries.set(e,n),n}rederive(e,t){let n=ZY(e),{watch:r}=this.watchers.follow(t.bound.held,n,n=>this.heard(e,t,n));t.bound={derived:n,held:r},this.report(e,t)}heard(e,t,n){let r=t.bound.derived.reached;if(this.rederive(e,t),!(n.kind!==`failed`&&!r&&!t.bound.derived.reached))for(let e of t.subscribers.keys())e()}report(e,t){let n=this.faultOf(e,t);for(let e of t.subscribers.values())e(n)}faultOf(e,t){return lV(`watch_file ${e}`,t.bound,zc(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const ZY=e=>cV({named:[e],whole:[e]});var QY=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Pe,n=e.ledger??new uY(t);this.watchMgr=new XY(e.watchers??new hV({clock:e.clock}),e.fileEvents??Pc);let r=r=>new IY({name:`source.${r}`,scope:`daemon`,keyOf:e=>e.digest,fields:({digest:e,identity:t},n)=>`digest=${en(e)} where=${R(WY(t.read))} sharedBy=${n}`,read:async({identity:t},n)=>{let r=qY(e.launcher,t.read,n);return YY(await r.read(),JY(t.parse),r.where)},every:({identity:{refresh:e}})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:({digest:e,identity:t},n)=>{if(t.refresh.kind!==`watch_file`)return FY();let r=this.watchMgr.subscribe(t.refresh.path,n,t=>(0,X.runInAction)(()=>{t===null?this.faults.delete(e):this.faults.set(e,t)}));return()=>{r(),(0,X.runInAction)(()=>this.faults.delete(e))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let{digest:n}=t,r=this.byKind[t.identity.read.kind].declare(e,t);return{digest:n,current:()=>r.current(),fault:()=>this.faults.get(n)??null}}stats(){return{shell:this.byKind.shell.stats(),file:this.byKind.file.stats(),watches:this.watchMgr.size()}}close(){this.byKind.shell.close(),this.byKind.file.close(),this.watchMgr.dispose()}};function $Y(e,t,n,r){return new Map([...n].map(([n,i])=>[n,r(n,()=>e.declare(t,i))]))}function eX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function tX(e){return{...Object.fromEntries(wx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:tG(e.preset)}}}const nX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function rX(e){if(ko(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return ko(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const iX=10*1e3;function aX(e,t){if(!(t<60))return e*3600/t}function oX(e,t,n,r){let i=r-t;if(i<50||i>iX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function sX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=oX(t.input,t.atMs,n.input,n.atMs),i=oX(t.output,t.atMs,n.output,n.atMs),a=oX(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 cX(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>iX)continue;let o=oX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function lX(e){return OJ(e.termCols??120)}function uX(e,t){return Zo(Xo(e.claudeConfigDir,t))}function dX(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function fX(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${x(t)}`),a=`${e}: ${String(t)}`}n.set(e,A(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage()),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.refresh(o,r.transcript_path)),c(`metrics`,()=>i.metricsProvider.refresh(o,r.transcript_path)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(He(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(uX(a,i.home)))])}function pX(e,{plugins:t,runs:n}){let r=IJ(e);return{git:r,tmux:r,hostName:r,hostUser:r,today:r,sources:new Map([...t.keys()].map(e=>[e,r])),runs:new Map([...n.keys()].map(e=>[e,{digest:e,current:()=>r.current(),fault:()=>null}]))}}function mX({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,t.workspace?.project_dir]}function hX(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${x(t)}`),IJ(L(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...mX(n))),tmux:i===null?IJ(I):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r.plugins].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.hookData.session_id))])),runs:$Y(e.sourceRuns,t,r.runs,(e,t)=>({digest:e,fault:()=>null,...o(`run ${en(e)}`,t)}))},faults:a}}function gX(e,t){let{deps:n}=e,r=e.hookData.session_id,i=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${x(t)}`),L(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:t.git.current(),usage:i(`session`,()=>n.usageStore.usageOf(r)),context:i(`context`,()=>n.contextProvider.tokensOf(r)),metrics:i(`metrics`,()=>n.metricsProvider.foldOf(r)),activity:i(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:t.tmux.current(),hostName:t.hostName.current(),hostUser:t.hostUser.current(),cache:i(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:i(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:i(`autocompact`,()=>n.autoCompact.stored(uX(e.hints,n.home))),sources:new Map([...t.sources].map(([e,t])=>[e,t.current()])),runs:new Map([...t.runs].map(([e,t])=>[e,{reading:t.current(),fault:t.fault()}]))},today:i(`today`,()=>_X(t.today,n.usageStore,r)),faults:kY.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{kind:`lane`,lane:e,reason:t.reason}]})}}function _X(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function vX({builtins:e,sources:t,runs:n},r){return[e.git,e.tmux,e.hostName,e.hostUser,...Object.values(t),...[...r].map(e=>(n[e.digest]??jY).reading)].some(yX)}const yX=e=>e.kind===`pending`&&e.why===`unread`;async function bX(e,t,n,r,i,a){await fX(e,t,n);try{await(0,X.when)(()=>!vX(r(),i()),{signal:a})}catch(e){if(!a.aborted)throw e}}function xX(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?Oo(t.why):void 0}const SX=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function CX(e,t,n){let{hookData:r,hints:i}=t,a=r.session_id,{effective:o,configFacts:s}=n,{configPath:c,...l}=s,u=e.builtins,d={usage:DY(SX(u.session),r),context:vY(SX(u.context),r),metrics:EY(SX(u.metrics),r),activity:SX(u.activity),cache:SX(u.cache),speed:SX(u.speed),autoCompact:SX(u.autocompact),git:SX(u.git),pr:SX(u.pr),tmux:SX(u.tmux),hostName:SX(u.hostName),hostUser:SX(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return Oo(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},p=e=>e.kind===`ok`?e.value:void 0,m=i.tmux??null,h=d.git.kind===`pending`?Oo(d.git.why):d.git.kind===`ok`?FX(d.git.value,d.pr,Oo):void 0,g=d.tmux.kind===`pending`?Oo(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?Oo(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?Oo(d.hostUser.why):p(d.hostUser),y=xX(d.context)??AX(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=xX(d.usage,d.metrics)??DX(p(d.usage)?.cost,p(d.metrics)?.sessionDuration),C=f(d.speed,OX),w=f(d.usage,e=>NX({cost:e.cost,tokens:e.tokens})),T=f(d.metrics,e=>NX({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),ee=f(d.activity,jX),te=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),E=f(d.cache,e=>({expiresAt:e})),ne=PX(t.home),D=r.workspace?{...r.workspace,current_dir:PX(r.workspace.current_dir)??``,project_dir:PX(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>PX(e)??e)}:r.workspace;return{...r,...D!==void 0&&{workspace:D},...ne!==void 0&&{home:ne},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:PX(r.location.main)??``}},...m!==null&&{tmux:{pane:m.pane,...g!==void 0&&{session:g}}},host:{..._!==void 0&&{name:_},...v!==void 0&&{user:v},...i.ssh!==void 0&&{ssh:i.ssh}},...tX(o),history:n.history,navigation:{back:n.back},term:{cols:lX(i)},...l,...c!==null&&{configPath:c},resumeCommand:OY(D,a,i.claudeConfigDir),...w!==void 0&&{session:w},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...E!==void 0&&{cache:E},...te!==void 0&&{context:te},...T!==void 0&&{metrics:T},...ee!==void 0&&{activity:ee},...y!==void 0&&{autocompact:y},...EX(n.sources,t=>{let n=SX(wX(e,t));return n.kind===`pending`?Oo(n.why):n})}}const wX=(e,t)=>e.sources[t]??Oo(`unread`);function TX(e,t,n){let r=[...e.map(e=>[e,wX(n,e)]),...[...t].map(([e,t])=>[e,t.kind===`ok`?(n.runs[t.value.digest]??jY).reading:t])];return{sources:String(r.length),sourcesPending:r.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`,sourcesFailed:r.flatMap(([e,t])=>t.kind===`failed`?[e]:[]).join(`,`)||`-`}}function EX(e,t){let n=Object.fromEntries(_k.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function DX(e,t){let n=e!=null&&t!=null?aX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function OX(e){let t=sX(e),n=cX(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function kX(e,t){if(e.kind===`pending`)return Oo(e.why);if(e.kind!==`ok`)return;let n=VJ(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}function AX(e,t){switch(e.kind){case`pending`:return Oo(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return FN(e.value,t)}}function jX(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=MX(e.running),i=MX(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 MX(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function NX(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 PX(e){return e===void 0||e.length===0||E.sep!==`\\`?e:e.replace(/\\/g,`/`)}function FX(e,t,n){let r=e=>e.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=r(qq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Jq(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts,...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const IX=(e,t)=>[...e].some(e=>e===t||e.startsWith(`${t}.`)),LX={pullRequests:e=>Object.keys(nX).some(t=>e.has(`git.${t}`)),rateLimits:e=>IX(e,`block`)||IX(e,`weekly`)};function RX(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]),...Object.values(n.partials??{})]:[]}function zX(e,t){let n=OU(e),r=new Map(YR(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=EU(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function BX(e,t){let n=new Map;for(let r of Uy(_S(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=>eb(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,zX(e,[...RX(e,t),...n.get(t)])])),a=e=>r.filter(t=>LX[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
|
|
193
193
|
/*!
|
|
194
194
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
195
195
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -217,9 +217,9 @@ Config tooling:
|
|
|
217
217
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
218
218
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
219
219
|
*/
|
|
220
|
-
function
|
|
220
|
+
function VX(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function HX(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+=`
|
|
221
221
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
222
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
222
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=VX(t.toml,t.ptr),i=HX(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})}};
|
|
223
223
|
/*!
|
|
224
224
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
225
225
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -247,7 +247,7 @@ function HX(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
247
247
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
248
248
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
249
249
|
*/
|
|
250
|
-
function
|
|
250
|
+
function UX(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+=`
|
|
251
251
|
`: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)}
|
|
252
252
|
/*!
|
|
253
253
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -276,7 +276,7 @@ function WX(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
276
276
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
277
277
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
278
278
|
*/
|
|
279
|
-
let
|
|
279
|
+
let WX=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var GX=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(WX);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}};
|
|
280
280
|
/*!
|
|
281
281
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
282
282
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -304,7 +304,7 @@ let GX=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
304
304
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
305
305
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
306
306
|
*/
|
|
307
|
-
function
|
|
307
|
+
function KX(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function qX(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function JX(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?aZ(e):iZ(e);return e.d++,t}return r===34||r===39?UX(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?YX(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?QX(e,r,t):e.s.charCodeAt(e.p+2)===58?$X(e,r,t):YX(e,e.p,r,0,t)}function YX(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||qX(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return XX(e,t,16,i);if(a===98)return XX(e,t,2,i);if(a===111)return XX(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else KX(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!qX(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:KX(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):ZX(e,c,10,t)}function XX(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!qX(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):KX(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(`_`,``)),ZX(e,o,n,t)}function ZX(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 QX(e,t,n){let r=e.p++,i;if(!KX(t)||!KX(e.s.charCodeAt(e.p++))||!KX(e.s.charCodeAt(e.p++))||!KX(e.s.charCodeAt(e.p++)))return YX(e,e.p=r,t,0,n);if(e.p+=5,KX(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,!KX(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return eZ(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(;KX(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return eZ(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return eZ(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return eZ(e,e.s.slice(r,e.p),2,i,r)}function $X(e,t,n){let r=e.p;if(!KX(t)||!KX(e.s.charCodeAt(++e.p)))return YX(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;KX(e.s.charCodeAt(++e.p)););return eZ(e,e.s.slice(r,e.p),4,!1,r)}function eZ(e,t,n,r,i,a){if(e.ld){let a=new GX(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)}}
|
|
308
308
|
/*!
|
|
309
309
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
310
310
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -332,7 +332,7 @@ function qX(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
332
332
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
333
333
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
334
334
|
*/
|
|
335
|
-
function
|
|
335
|
+
function tZ(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 nZ(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;tZ(e)}}
|
|
336
336
|
/*!
|
|
337
337
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
338
338
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -360,7 +360,7 @@ function nZ(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
360
360
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
361
361
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
362
362
|
*/
|
|
363
|
-
function
|
|
363
|
+
function rZ(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(UX(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 iZ(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(nZ(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=rZ(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),nZ(e,!0,!0);let l=JX(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),nZ(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 aZ(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(nZ(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(JX(e,93)),nZ(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)}
|
|
364
364
|
/*!
|
|
365
365
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
366
366
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -388,7 +388,7 @@ function iZ(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
388
388
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
389
389
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
390
390
|
*/
|
|
391
|
-
function
|
|
391
|
+
function oZ(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 sZ(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 cZ(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++,nZ(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=rZ(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=oZ(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(sZ(n,u,a),o=!0)}else{a=n.p;let e=oZ(n,rZ(n),s,c,0);!e&&!o&&sZ(n,e,a),nZ(n,!0,!0);let t=JX(n,void 0);e&&!o&&(e[1][e[0]]=t)}nZ(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),nZ(n)}return r}``.isWellFormed;
|
|
392
392
|
/*!
|
|
393
393
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
394
394
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -416,7 +416,7 @@ function sZ(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
|
|
|
416
416
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
417
417
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
418
418
|
*/
|
|
419
|
-
const
|
|
419
|
+
const lZ=e=>e.codePointAt(0).toString(16).toUpperCase(),uZ=String.raw`
|
|
420
420
|
ObjC.import("AppKit");
|
|
421
421
|
ObjC.import("CoreText");
|
|
422
422
|
function lacksOf(font, points) {
|
|
@@ -463,54 +463,54 @@ function run(argv) {
|
|
|
463
463
|
: iterm(argv[1], points),
|
|
464
464
|
);
|
|
465
465
|
}
|
|
466
|
-
`;async function
|
|
467
|
-
`).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
|
|
468
|
-
`,`:family=${
|
|
469
|
-
`)){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
|
|
466
|
+
`;async function dZ(e,t){let n=await e.launch({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,uZ,...t],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new Bq(`the font`);return{kind:`failed`,reason:`osascript failed (${Ze(n)})`}}let r;try{r=JSON.parse(n.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(n.stdout.trim())}, not JSON`}}return typeof r==`object`&&r&&`error`in r?{kind:`failed`,reason:r.error}:{kind:`ok`,value:r}}const fZ=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),pZ=e=>[...e].map(lZ).join(`,`);async function mZ(e,t,n){let r=await dZ(e,[`font`,t.kind,t.name,pZ(n)]);if(r.kind===`failed`)return r;let{lacks:i}=r.value;return{kind:`ok`,value:{font:t.name,lacks:i===null?null:fZ(i)}}}function hZ(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=>!Hj(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const gZ=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function _Z(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=>hZ(e,n));if(t!==null)return r[0];let i=r.find(e=>!gZ(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`}}}async function vZ(e,t,n,r){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let i=n.ITERM_PROFILE??null,a=await dZ(e,[`iterm`,i??``,pZ(r)]);return a.kind===`failed`?a:_Z(a.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:fZ(e.lacks)})),i,t)}function yZ(e,t){let n=e.split(`
|
|
467
|
+
`).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 bZ=e=>e.replace(/[\\:,=-]/g,`\\$&`);async function xZ(e,t,n){let r=await e.launch({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
468
|
+
`,`:family=${bZ(t)}`],timeoutMs:3e3,category:`doctor.font`});if(!r.ok){if(r.reason===`rate-limited`)throw new Bq(`the font`);return{kind:`failed`,reason:`fc-match failed (${Ze(r)})`}}return yZ(r.stdout,n)}function SZ(e,t,n){return process.platform===`darwin`?mZ(e,t,n):xZ(e,t.name,n)}function CZ(e,t){let n=t||E.join(e,`.config`);return[E.join(n,`alacritty`,`alacritty.toml`),E.join(n,`alacritty.toml`),E.join(e,`.config`,`alacritty`,`alacritty.toml`),E.join(e,`.alacritty.toml`)]}function wZ(e){return e===`darwin`?`Menlo`:`monospace`}const TZ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function EZ(e){let t=TZ(e.font)?e.font:{},n=TZ(t.normal)?t.normal:{},r=(TZ(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 DZ(e,t,n){let r;try{r=s.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=cZ(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=EZ(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(`~/`)?E.join(t,r.slice(2)):E.resolve(E.dirname(e),r);if(!s.existsSync(i))continue;let a=DZ(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}async function OZ(e,t,n,r){let i=CZ(r,t.XDG_CONFIG_HOME).find(e=>s.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:DZ(i,r,0);if(a.kind===`failed`)return a;let o=a.value?.family??wZ(process.platform),c=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),l=await SZ(e,{kind:`family`,name:o},n);if(l.kind===`failed`)return l;let{font:u,lacks:d}=l.value;return{kind:`ok`,value:{font:u,from:u===o?c:`${c}; ${o} as fontconfig matches it`,lacks:d}}}const kZ={iterm2:vZ,alacritty:(e,t,n,r,i)=>OZ(e,n,r,i)};function AZ(e,t,n,r,i){return kZ[t.name](e,t.version,n,r,i)}function jZ(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 MZ=e=>CB(e,`doctor-post-mortems-read.json`,{through:null},jZ);function NZ(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const PZ={realpath:e=>NZ(()=>s.realpathSync(e)),checkoutOf:nn,digest:e=>NZ(()=>$t(e)),nativeShipped:hs(process.platform,process.arch)};function FZ(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(E.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 IZ=e=>({marks:Iq(e),clicked:zq(e),postMortemsRead:MZ(e)}),LZ=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function RZ(e){let t=new Map,n=(e,n)=>{let r=JSON.stringify(e),i=t.get(r)??n();return t.set(r,i),i};return{...e,probeTmux:t=>n([`tmux`,t],()=>e.probeTmux(t)),remoteLogin:t=>n([`remote`,t],()=>e.remoteLogin(t)),fontInUse:(t,r,i)=>n([`font`,t,r,i],()=>e.fontInUse(t,r,i))}}function zZ(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 BZ=/^(sshd|mosh-server)\b/;function VZ(e,t){let n=Gq(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of Kq(n,t))if(BZ.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}async function HZ(e,t){let n=await e.launch({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!n.ok){if(n.reason===`rate-limited`)throw new Bq(`the processes`);return{kind:`failed`,reason:`ps failed (${Ze(n)})`}}return VZ(n.stdout,t)}const UZ=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function WZ(e,t){let n=[];for(let r of e.split(`
|
|
469
|
+
`)){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 GZ(e){let t;try{t=s.realpathSync(e)}catch{return!1}let n=UZ.exec(t)?.[1];return n!==void 0&&s.existsSync(E.join(n,`bin`,`cc-candybar`))}async function KZ(e){let t=await e.launch({bin:`ps`,args:[`-U`,String(o.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});return t.ok?{kind:`ok`,value:WZ(t.stdout,GZ)}:{kind:`failed`,reason:`ps failed (${Ze(t)})`}}async function qZ(e,t){let n=await pc(e,t,`doctor.tmux`,[`display`,`-p`,`-t`,t.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(n.kind===`rate-limited`)throw new Bq(`tmux`);return n.kind===`failed`?{kind:`failed`,reason:n.reason}:zZ(n.stdout)}function JZ(e,t,n){return{probeTmux:t=>qZ(e,t),remoteLogin:t=>HZ(e,t),fontInUse:(t,r,i)=>AZ(e,t,r,i,n.home),loadConfig:t,home:n.home,managedSettingsDir:n.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??iee(process.platform),install:PZ,daemons:()=>KZ(e),forge:t=>$Z(e,t),transcript:XZ}}function YZ(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
470
470
|
`)+1,i=n.lastIndexOf(`
|
|
471
471
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
472
|
-
`)){let t=
|
|
473
|
-
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const
|
|
474
|
-
`:null,r=
|
|
472
|
+
`)){let t=tY(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function XZ(e){let t=qo(e,oM+1);return t.kind===`ok`?F(YZ(t.value.buf,t.value.fromStart)):t}function ZZ(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 QZ={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function $Z(e,t){if(Wz(t)===void 0)return{kind:`ok`,value:null};let n=fJ(await e.launch({bin:`git`,args:[...dJ],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=_J(n.value);if(r===null)return{kind:`ok`,value:null};let i=uJ(r);if(i===null)return{kind:`ok`,value:null};let a=aJ[i],o=QZ[i],s=o.loginHost(lJ(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return eQ(a,s,o.nonZero,c)}function eQ(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):oJ(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:nJ(r.stderr)}):{kind:`failed`,reason:tJ(e,r)}}function tQ(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
473
|
+
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const nQ=e=>NZ(()=>aee(e));function rQ(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:Zo(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:nQ(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))}}async function iQ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function aQ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Yj(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:Jj(t),tmuxClient:t}}}}async function oQ(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(Rj(s))return{kind:`bundling`,name:s,version:c};if(!zj(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await 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`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function sQ(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};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"}}}async function cQ(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function lQ(e,t,n,r){return{pullRequests:await cQ(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await cQ(t.rateLimits,()=>r)}}function uQ(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}}}}async function dQ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=cG(d.config,r,()=>!1),p=await iQ(e,t.tmux),m=aQ(p,t.terminalEnv),h=[...new Set([...Sj(f),...xj(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:oQ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),lQ(e,BX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:tQ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:ZZ(e,o),claudeSettings:rQ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Zo(Xo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function fQ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;Dn(e,fo(es(e),t.path,JSON.stringify(t.value),Za));let r=e=>({...e,sources:nQ(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||Rr(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 pQ={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},mQ=16384;var hQ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}accepted=0;accept(){return{id:++this.accepted,at:this.clock.monotonic()}}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessDraining=0;subprocessDrainedBytes=0;subprocessDrainsCut=0;subprocessPipeErrors=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}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)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)},onDrainOpen:()=>{this.subprocessDraining++},onDrainRead:(e,t)=>{this.subprocessDrainedBytes+=t},onDrainClose:(e,t)=>{this.subprocessDraining--,t===`cut`&&this.subprocessDrainsCut++},onPipeError:()=>{this.subprocessPipeErrors++}};recordRollingNow(){let e=this.clock.monotonic();if(this.rollingTimestamps.length<mQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%mQ}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=this.clock.monotonic()-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,refused:Object.fromEntries(this.subprocessRefused),draining:this.subprocessDraining,drainedBytes:this.subprocessDrainedBytes,drainsCut:this.subprocessDrainsCut,pipeErrors:this.subprocessPipeErrors,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0,monotonic:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},sourceRuns:{shell:pQ,file:pQ,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,due:0,retiredViews:0,accountedBytes:0,budgetBytes:0},collector:{sessions:0,retiring:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running: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,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,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:tn,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.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},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,sourceRuns:e.sourceRuns,transcriptReads:e.transcriptReads,renderCache:e.renderCache,collector:e.collector,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const gQ={connectMs:200,budgetMs:500};async function _Q(e,t){return vQ(await yQ(e),t.includes(`--json`))}function vQ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${fr(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
474
|
+
`:null,r=bQ(e.value);return r===null?{stdout:n??OQ(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function yQ(e){return ar(e,()=>({kind:`stats`}),gQ,e=>`stats`in e?e.stats:void 0)}function bQ(e,t=xQ){let n=hQ.referenceSnapshot(),r=SQ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=wQ(e.version,e.sourceDigest??null),a=wQ(tn,an());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 xQ=Object.keys(hQ.referenceSnapshot());function SQ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!CQ(e))return[];if(!CQ(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(...SQ(e[i],t[i],a)):r.push(a)}return r}function CQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wQ(e,t){return`${e} [${t===null?`no digest`:en(t)}]`}function TQ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function EQ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function DQ(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 OQ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${wQ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${DQ(e.uptimeSec)}`),t.push(` rss ${TQ(e.rssBytes)}`),t.push(` heapUsed ${TQ(e.heapUsedBytes)}`),t.push(` heapTotal ${TQ(e.heapTotalBytes)}`),t.push(` external ${TQ(e.externalBytes)}`),t.push(` arrayBuffers ${TQ(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(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${EQ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${EQ(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(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Vc(e.fileEvents)}`);for(let n of[`shell`,`file`]){let r=e.sourceRuns[n];t.push(` runs.${n.padEnd(8)} entries=${r.entries} held=${r.held} failures=${r.failures} abandoned=${r.abandoned} last=${r.lastMs===null?`-`:`${r.lastMs}ms`}`)}t.push(` runs.watches ${e.sourceRuns.watches}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${TQ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${TQ(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(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` due ${e.renderCache.due}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${TQ(e.renderCache.accountedBytes)} / ${TQ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`collector`),t.push(` sessions ${e.collector.sessions}`),t.push(` retiring ${e.collector.retiring}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),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(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`),t.push(` draining ${e.subprocesses.draining} (${e.subprocesses.drainedBytes} bytes dropped, ${e.subprocesses.drainsCut} cut)`),t.push(` pipeErrors ${e.subprocesses.pipeErrors}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
475
475
|
`)+`
|
|
476
|
-
`}const
|
|
477
|
-
`).join(` — `));let n=
|
|
478
|
-
`);return{inMode:r!==`0`,screen:i}}function n$(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`]}async function r$(e,t,n){let r=await e$(e,t,`claude-input.type`,n$(t.pane,`cc-candybar-slash`,[`C-s`]),n);return r.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${r.reason})`}}function i$(e){return{read:t=>t$(e,t),type:(t,n)=>r$(e,t,n)}}const a$=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function o$(e){let t=tq(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function s$(e){return XG(()=>decodeURIComponent(e))}const c$=5e3;function l$(e,t,n){if(e.reason===`rate-limited`){n(`warn`,Ze(e));return}throw e.reason===`aborted`?new JG(t):Error(`${t} failed (${Ze(e)})`)}async function u$(e,t,n,r){let i=await e.launch({...t,timeoutMs:c$});i.ok||l$(i,n,r)}async function d$(e,t,n,r,i,a){let o=p(E.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:E.join(o,`stderr`),status:E.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){l$({...s,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(s.pid),l=kt(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;l$(l.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:h(a.stderr,`utf8`),exitCode:l.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await Le(e.clock,50)}}finally{_(o,{recursive:!0,force:!0,maxRetries:3})}}function f$(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const p$=(e,t)=>f$(s$(e),t),m$=new Set([`request`,`feed`]);function h$(e){if(!m$.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const g$=async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n),o=t.diagnosticCopy(a,h$(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open the indicator beside the settings door again and copy from there`);await f$(o,t)},_$=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,s$(e)],category:`click.open`},`open -a "Visual Studio Code"`),v$=async(e,t)=>{let n=o$(s$(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},y$=async(e,t)=>{let[n=``,...r]=XG(()=>wa(e)),i=o$(n),a=t.gates.state.gateFor(N$(t,i));if(r.length===0)throw new Z(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Z(`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 Z(`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 Z(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}C$(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},b$=/^-?\d+$/;function x$(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const S$=async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!b$.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=N$(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new Z(`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&&b$.test(u)?w$(l,parseInt(u,10)):T$(`step-state`,r,l,FG(s,e=>t.sessionState.get(a,e),r)),f=x$(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);C$(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function C$(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Hk));if(i.length===0)return;let a=wG(N$(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function w$(e,t){return Math.max(e.min,Math.min(e.max,t))}function T$(e,t,n,r){if(r===null)return n.min;if(!b$.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return w$(n,parseInt(r,10))}function E$(e,t,n){let r=t.get(n,qG);return r===null?e:{...e,target:{source:`pick`,path:r}}}function D$(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function O$(e){let t;try{t=JSON.parse(e)}catch{throw new Z(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Z(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Z(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:D$(a,i)}}function k$(e,t){let n=j$(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function A$(e,t){let n=e.sessionState.get(t,GG);return n===null?null:O$(n)}function j$(e,t){let n=A$(e,t);return n===null?null:E$(n,e.sessionState,t)}function M$(e,t,n){let r=j$(e,t);if(r===null)return;let{path:i}=I$(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function N$(e,t){return e.configFor(k$(e,t))}function P$(e,t){let n=A$(e,t);if(n===null)return null;let r=()=>e.lanes.of(E$(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function F$(e,t){let n=j$(e,t);return n===null?LG:VG(e.configFor(n))}function I$(e,t){return bB(e.locations,nV(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function L$(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const R$=async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n),o=k$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`set-config: ${l.reason}`);let u=I$(t,o),d=SG(s,e=>t.sessionState.get(a,e),r);zK(L$(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},z$=async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!b$.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=k$(t,a),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(r);if(!u)throw new Z(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=I$(t,s),f=SG(c,e=>t.sessionState.get(a,e),r),p=RK(d.path,f.key),m=typeof p==`number`?w$(u,p):T$(`step-config`,r,u,IG(f.globals,r)),h=x$(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);zK(L$(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},B$=async(e,t)=>{let[n=``]=XG(()=>wa(e)),r=o$(n),i=k$(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=bG(a,o),c=CG(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save: ${t.reason}`);return[e.target,t.value]});H$(`save`,l,c);let d=I$(t,i);BK(L$(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.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(V$)].join(` `)} → ${d.path} (session=${r})`)},V$=e=>`${e.preset}/${e.id}.settings.${e.setting}=${ub(e.value)}`;function H$(e,t,n){for(let r of n){let n=t.validate(r.key,ub(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const U$=async(e,t)=>{let[n=``]=XG(()=>wa(e)),r=o$(n),i=k$(t,r),a=t.configFor(i),o=DG(a,e=>t.sessionState.get(r,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save-preset: ${t.reason}`);return[e.configKey,t.value]});H$(`save-preset`,s,o.placements);let l=I$(t,i),u=qK(L$(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Px.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Mx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(V$)].join(` `)} → ${l.path} (session=${r})`)},W$=async(e,t)=>{let[n=``]=XG(()=>wa(e)),r=o$(n),i=k$(t,r),a=kG(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Z(`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=I$(t,i);JK(L$(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(bG(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Ex.map(e=>Mx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Ex.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},G$=async(e,t)=>{let[n=``,r=``]=XG(()=>wa(e)),i=o$(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=k$(t,i),o=I$(t,a);YK(L$(t,i),o,r),t.reloadConfig(a);let s=Mx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},K$=async(e,t)=>{let[n=``,...r]=XG(()=>wa(e)),i=o$(n),a=k$(t,i),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Z(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=I$(t,a),l=r.map(AG),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);WK(L$(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function q$(e,t){let n=(e,t)=>[...Wy(vS(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(hS(t.presets).flatMap(e=>n(t,e).map(t=>Uk(OS(e),By(t)))));return hS(e.presets).flatMap(t=>n(e,t).map(e=>({member:Uk(OS(t),By(e)),node:e})).filter(({member:e})=>!r.has(e)))}function J$(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[zk]:[]])}const Y$=async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n),o=k$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`apply-layout-op: ${l.reason}`);let u=Zte(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=I$(t,o),f=XK(L$(t,a),d,r,u);t.reloadConfig(o);let p=J$(q$(s,t.configFor(o)),t.sessionState.get(a,zk)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},X$=async(e,t)=>{let[n=``]=XG(()=>wa(e)),r=o$(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),M$(t,r,i),t.log(`info`,`undo: restored ${wq(i)} (session=${r})`)},Z$=async(e,t)=>{let n=o$(s$(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(N$(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},Q$=async(e,t)=>{let n=o$(s$(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);M$(t,n,r),t.log(`info`,`rewind: put back ${wq(r)||`nothing`} as edit mode found it (session=${n})`)},$$=async(e,t)=>{let[n=``]=XG(()=>wa(e)),r=o$(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),M$(t,r,i),t.log(`info`,`redo: re-applied ${wq(i)} (session=${r})`)},e1=async(e,t)=>{o$(s$(e)),await t.applyUpdate()};function t1(e,t){let n=e.sessionState.get(t,KG);if(n===null)throw new Z(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Z(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Z(`client hints record is not an object: ${n}`);return zn(r)}function n1(e,t,n){let r=$M(n);e.sessionState.setBatch(t,gN(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${rN(n.config)} ${mN(n.nerdFont,n.marks)} ${iN(n.terminal,n.clicked)} ${aN(n.terminal,n.width)} ${oN(n.install)} ${cN(n.daemon)} ${lN(n.data)} ${pN(n.transcripts)} ${uN(n.frames,n.claudeSettings)} ${fN(n.claudeSettings.origin.sources)} (session=${t})`)}async function r1(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await fQ({...n,loadConfig:()=>r},t1(e,t),k$(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:Gq(i,a)},dQ(t,a),RZ(e.doctorStores))}catch(e){throw e instanceof Vq?new Z(e.message):e}let s={facts:o,install:IZ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(k$(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:r1(e,t,n,i)}};return s}const i1=(e,t)=>{let n=zZ(e.doctor);return r1(e,t,n,n.loadConfig(k$(e,t)))};async function a1(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=RZ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:cQ(e.arrival),install:i,clicked:o1(e,o)}}function o1(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?Xj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>zq(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const s1={gathers:!0,prepare:async(e,t)=>{let n=o$(s$(e)),r=await i1(t,n);return async e=>n1(e,n,await a1(e,n,r))}},c1=async(e,t)=>{let n=PQ(s$(e));if(n===null)throw new Z(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Z(`doctor-probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} delivery=${r.kind}`)},l1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=XG(()=>wa(e)),i=o$(n),a=eN(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await i1(t,i);return async e=>{let t=await a1(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Z(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=pQ(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Z(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${cM(n.fix)} (session=${i})`),n1(e,i,r.value)}}},u1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=XG(()=>wa(e)),a=o$(n),o=eN(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!aM.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${aM.join(` or `)}`);let s=await i1(t,a);return async e=>{let t=await a1(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Z(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>Iq(e,...r));if(c.kind===`failed`)throw new Z(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),n1(e,a,{...t,marks:c})}}},d1=async(e,t)=>{let[n=``,r=``]=XG(()=>wa(e)),i=o$(n),a=Object.values(t.configFor(k$(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Z(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(t1(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Z(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function f1([e=``,t=``,n=``,r=``],i){let a=o$(e),o=k$(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Z(`"${t}" is not a run action this session's config declares`);let l=qF(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Z(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Z(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Z(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],envOverlay:{...Nq({sessionId:a,projectDir:o.projectDir,claudeConfigDir:t1(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const p1=new Map([[Ki,a$(p$)],[Yi,a$(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Z(`load-config: expected <sessionId>/<path> (missing separator)`);let r=o$(XG(()=>decodeURIComponent(e.slice(0,n)))),i=XG(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Z(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Z(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,qG),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,qG,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[qi,a$(_$)],[Wi,a$(y$)],[Gi,a$(S$)],[Xi,a$(R$)],[Zi,a$(z$)],[na,a$(K$)],[Qi,a$(B$)],[$i,a$(U$)],[ea,a$(W$)],[ta,a$(G$)],[ra,a$(Y$)],[ia,a$(X$)],[aa,a$($$)],[oa,a$(Z$)],[sa,a$(Q$)],[Ji,a$(v$)],[ca,a$(e1)],[la,s1],[ua,l1],[da,u1],[fa,a$(c1)],[pa,a$(d1)],[`run`,a$(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=XG(()=>wa(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=f1(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[ma,a$(async(e,t)=>{let[n=``,r=``,i=``,a=``]=XG(()=>wa(e)),o=o$(n),s=i;if(!t.links.verify(iV(o,r,s),a))throw new Z(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=rV(nV(t.stateDir),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(k$(t,o))})],[ha,a$(g$)]]),m1=new Set([Wi,Gi,Xi,Zi,na,Qi,$i,ea,ta,ra,ia,aa,oa,sa,Ji,ca,la,ua,da,pa,`run`,ma,Yi,ha]);function h1(e,t){return g1(e===`dispatch`?Ea(t):[{verb:e,value:t}])}function g1(e){let t=e.find(e=>m1.has(e.verb)),n=t===void 0?``:XG(()=>eee(t.value));return n===``?null:tq(n)}const _1=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function v1(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function y1(e,t){let[n]=Oa(Ea(e)),r=n===void 0?void 0:p1.get(n.verb);return r?.gathers?_1(r,n.value,t):void 0}async function b1(e,t,n){let r=[],i=!1,a=Ea(e),o=g1(a);for(let[e,{verb:o,value:s}]of Oa(a).entries()){let a=p1.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await v1(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof JG)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Z||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&hc(t.sessionState,o.id,r.join(`
|
|
479
|
-
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function x1(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function S1(e,t,n,r){let i=e===null?null:P$(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}x1(e)}),c=[],l=e=>WG(e,e=>F$(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(u$(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed($Q(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=j$(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}x1(c)}function C1(e,t,n){return async(r,i)=>{let a=h1(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>S1(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const w1=new Map([...[...p1].map(([e,t])=>[e,C1(e,async(e,n)=>t.gathers?_1(t,e,n):void 0,(e,n,r)=>v1(t,e,n,r))]),[Ui,C1(Ui,y1,b1)],[fa,c1]]);Object.freeze([...w1.keys()]);function T1(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>S1(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=UG(F$(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:gi}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function E1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const D1=e=>ko(e);var O1=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,D1(n)||R1(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=D1(n)?null:r.now()}read(){let e=this.cell.get();if(D1(e))throw new lI(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){D1(e)||R1(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},k1=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${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_()}},A1=class{constructor(e){this.deriver=e}read(){return this.deriver()}},j1=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new k1(`Variable "${e}"`,()=>{let e=n();return R1(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},M1=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new A1(()=>{let e=n();return R1(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},N1=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(L1(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=L1(e);I1(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},P1=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new k1(`Variable "${e}"`,()=>L1(t()),I1)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function F1(e){return JSON.stringify(e)}function I1(e,t){return F1(e)===F1(t)}function L1(e){return e.kind===`ok`?{kind:`ok`,value:iI(e.value)}:e}function R1(e,t,n,r){let i=aI(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var z1=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new O1(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new N1(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new P1(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?j1:M1;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new A1(n);let r=new k1(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];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()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof N1))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}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`){let e=t.read();return e.kind===`pending`?e:F(F1(e))}try{return F(String(t.read()))}catch(e){return uI(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):Oo(`unread`)}}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.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof j1||t instanceof P1)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}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}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}};function B1(e){return V1(e,new Set(e.names()),``)}function V1(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!U1(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:W1(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return V1(e,t,a)}})}function H1(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 U1(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function W1(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new lI(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function G1(e){return oe(`sha256`).update(JSON.stringify(K1(e))).digest(`hex`)}function K1(e){return Array.isArray(e)?e.map(K1):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,K1(t)])):e}const q1=e=>({digest:G1(e),identity:e});function J1(e){return ae.createHash(`sha256`).update(e).digest(`hex`)}function Y1(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(k(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function X1(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]}"`)}}function Z1(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,source:e.regex.source,flags:e.regex.flags};case`json`:return{kind:`json`}}}const Q1={session:()=>{throw new lI(`session_id`,`the view's session has no value yet: no view source is bound`)},read:()=>Oo(`unread`),run:()=>MY,drawnAt:()=>{throw new lI(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},$1=e=>({kind:`found`,value:e});function e0(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&ko(n))return n;if(typeof n!=`object`||!n)return $1(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&ko(n)?n:$1(n)}function t0(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the config declares`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function n0(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`?oI(e):t===`number`?sI(e):cI(e)}function r0(e){return e===`number`?0:e===`boolean`?!1:``}var i0=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];runs=X.observable.map(void 0,{deep:!1});runSourcesNow=(0,X.computed)(()=>new Map([...this.runs].map(([e,t])=>[e,t.get()])));namedNow=(0,X.computed)(()=>new Map([...this.runSourcesNow.get()].flatMap(([e,t])=>t===void 0?[]:[[e,t]])));runSources(){return this.runSourcesNow.get()}namedRuns(){return this.namedNow.get()}subscriptionsNow=(0,X.computed)(()=>[...new Map([...this.namedNow.get().values()].map(e=>[e.digest,e]))].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e));subscriptions(){return this.subscriptionsNow.get()}inputs=X.observable.box(Q1,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=TU({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i={}){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.env=i,this.sessionState=n,this.cleanups.push((0,X.observe)(this.subscriptionsNow,()=>{}))}view(){return new e(new z1(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this,this.env)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,aI(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>t0(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new lI(e,`variable "${e}" has no value yet: its source has not answered`);let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=n0(a,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=this.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,{kind:`shell`,command:t,cwd:n.cwd},Y1(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r),a=this.registerCachePolicy(e,n),o=(0,X.computed)(()=>{let e=a();return e===void 0?void 0:q1({read:t,parse:Z1(r),refresh:e})},{equals:(e,t)=>e?.digest===t?.digest});(0,X.runInAction)(()=>{this.sourceNames.push(e),this.runs.set(e,o)}),this.cleanups.push((0,X.reaction)(()=>this.runFact(e)?.reading,e=>{if(e===void 0||e.kind===`pending`)return;let{at:t,...n}=e;i(n)},{fireImmediately:!0}))}runFact(e){let t=this.runs.get(e)?.get();return t===void 0?void 0:this.inputs.get().run(t.digest)}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,Eo(t,n))}}documentPublisher(e,t){let n=t===void 0?Oo(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(B1(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=n0(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=uI(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}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`,()=>{let e=n.get(this.session(),t.key);return e===null?r:e})}stateRevision(){return this.sessionState===void 0?0:this.sessionState.revision(this.session())}session(){return this.inputs.get().session()}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.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 new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.store.dispose()}registerCachePolicy(e,t){switch(t.kind){case`never`:return()=>({kind:`never`});case`ttl`:return()=>({kind:`ttl`,durationMs:t.durationMs});case`watch_file`:return this.cleanups.push((0,X.reaction)(()=>this.runFact(e)?.fault??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0})),()=>({kind:`watch_file`,path:t.path});case`key`:{let n=this.engine.parse(t.template);return this.answeredUnder(e,()=>{try{return F(n.evaluate(B1(this.store)).map(e=>e.plain).join(``))}catch(e){return uI(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):Oo(`unread`)}})}case`depends_on`:return this.answeredUnder(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?F(e.map(e=>e.value).join(`,`)):Oo(`unread`)})}}answeredUnder(e,t){let n=(0,X.computed)(t,{equals:X.compareStructural});this.cleanups.push((0,X.reaction)(()=>n.get(),t=>this.notePolicy(e,t),{fireImmediately:!0}));let r;return()=>{let e=n.get();return e.kind===`ok`&&(r=e.value),r===void 0?void 0:{kind:`key`,hash:J1(r)}}}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return n0(this.defaultEmptyValue,t)}catch{return r0(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.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 a0(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const o0={kind:`hidden`},s0={kind:`shown`};function c0(e,t){try{return a0(e,t)?s0:o0}catch(e){let t=uI(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function l0(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function u0(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function d0({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function f0({text:e,placement:t,lead:n,trail:r}){return{text:p0(e),placement:t,...n!==void 0&&{lead:p0(n)},...r!==void 0&&{trail:p0(r)}}}function p0(e){let t=e.blankCopy(e.plain);t.style=xA(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(xA(i).clearMetaAndLinks(),n,r);return t}function m0(e){let t=d0(e);if(t.length===1)return e.text;let n=l0(t);return n.style=e.text.style,n}function h0(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=l0(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:l0([d,...c],a)},...l.length>0&&{trail:l0([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(u0(u,n,p),[{text:u,...f}])}function g0(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return wj(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function _0(e,t){if(e.length===0)return 0;let{lines:n}=Tj(e.map(({owner:e})=>e),t),r=z(uj(n[n.length-1]));return Math.max(0,r-vj(t)+yj(t))}function v0(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=Tj([e],{...n,width:1/0});return z(uj(r.flat()))<=n.width}function y0(e,t,n,r){if(v0(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=_0(n,r);return i.divide(g0(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function b0(e,t){let n=Math.max(2,Cj(t)-vj(t)-t.padding);return x0(e,t).reduce((e,r)=>[...e,...y0(r,n,e,t)],[])}function x0(e,t){let n=()=>e.map(e=>({owner:m0(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=Tj(e.map(m0),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(uj(i.flat()))),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];u0(c,c.cellLength+a,n)}),n()}function S0(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=C0(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:xA(a.style)};if(e.style.link){i();let r=C0([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function C0(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>w0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function w0(e,t){let n=e.copy();return n.style=t,n}function T0(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 E0(e,t){let{look:n}=T0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function D0(e,t){let{layout:n}=T0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function O0(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 k0(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,A0(e,t,o,n,r,i));return i}function A0(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=ES(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,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=Lx.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=ES(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,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=ES(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:N0(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:N0(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(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:qF(n),argv:n.run.map(n=>N0(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,N0(e,r,t)])};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:N0(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 j0(e){return e.kind===`do`?j0(e.head):e}function M0(e){switch(j0(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`slash`:case`run`:case`do`:return!1}}function N0(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function P0(e,t){return e.has(t)?oI(e.read(t)):``}function F0(e,t){return T0(e,t).registry.session()}function I0(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function L0(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function R0(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([xA(e.style),r])});for(let t of e.spans)i.stylize(U.combine([xA(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function z0(e,t){return Math.max(e.members.indexOf(P0(t,e.stateVar)),0)}function B0(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=P0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=P0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=P0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(z0(e,r)+1)%e.members.length];return{effects:[{verb:Wi,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Gi,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ki,args:[I0(e.text,B1(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[I0(e.target,B1(r))]}],active:!1};case`persist-literal`:{let t=P0(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=P0(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(z0(e,r)+1)%e.members.length];return{effects:[{verb:Xi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Zi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:na,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`redo`:return{effects:[{verb:aa,args:[i]}],active:!1};case`back`:return{effects:[{verb:oa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:sa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:ea,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ta,args:[i,I0(e.name,B1(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:la,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ua,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:da,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:pa,args:[i,e.line]}],active:!1};case`run`:{let t=B1(r),n=JSON.stringify({run:e.argv.map(e=>I0(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,I0(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:ra,args:[i,e.key,CF(e.op)]}],active:!1};case`do`:{let o=B0(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>B0(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:ra,args:[i,e.key,CF(r)]}],active:!1}}}}function V0(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:bi(`action "${e}"`,n,t.members.length,z0(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 H0(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=T0(n,`action "${e}"`).store,{display:a,boundValue:o}=V0(e,j0(r),t,i),s=F0(n,`action "${e}"`),{effects:c,active:l}=B0(r,a.plain,o,i,s,n.signer);return R0(a,Ta(c),l)}function U0(e){return{action:{fn:(t,...n)=>H0(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function W0(e,t){return L0(`✕`,Ta([{verb:Wi,args:[e,t,gi]}]),!1)}function G0(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(kv(e,t,n))})}function K0({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function q0(e,t,n){return new U({color:H.fromRgba(Uu(e.get(`warning`),t,Ov,n))})}function J0(e,t,n){return U.combine([G0(e,t,n),q0(e,t,n)])}function Y0(e,t,n){return K0(Vv(e.palette,e.disclosure,t,n))}function X0(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(j_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const Z0=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},Q0=e=>new U({bold:e});function $0(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>Z0(a,U.combine([Y0(e,{...n,distribution:t},i),Q0(o)]));let o=G0(e.palette,a,i);return(e,t,i,a)=>e2(i,U.combine([o,Q0(a)]),r(t,n))}const e2=(e,t,n)=>Z0(K.fromFragments([Z0(e,t),Z0(` `,t),X0(n)]));function t2(e,t,n,r){return t===void 0?Z0(r):e2(r,void 0,t(n,e))}function n2(e,t,n,r,i){let a=G0(e.palette,i,r);return(e,r,i,o)=>Z0(K.fromFragments([Z0(o?`[`:` `,a),X0(n(r,t)),Z0(o?`]`:` `,a)]))}function r2(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=>i2(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function i2(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function a2(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function o2(e){return{current:null,drawnAt:e}}function s2(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 c2(e,t,n){return u2(e,()=>n(s2(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function l2(e,t){return u2(e,()=>(e.current=null,t()))}function u2(e,t){let n=e.current;try{return t()}finally{e.current=n}}function d2(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 f2(e){return new K(e).cellLength}function p2(e){let{width:t,chromeCols:n,padding:r}=T0(e,`a row fit`);return Math.max(1,t-n-2*r)}function m2(e){let{padding:t,seamCols:n}=T0(e,`a row fit`);return Math.max(1,p2(e)-(f2(`✕`)+2*t+n))}function h2(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 g2(e,t,n){let r=f2(`←`)+1+f2(`→`)+1,i=h2(e,t,n);return(i.length>1?h2(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function _2(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function v2(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 y2(e,t,n){let r=e.compiled.get(t),i=r&&j0(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 b2(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=T0(a,`picker`).store,d=F0(a,`picker`),f=`stateVar`in t?P0(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`?m2(a):p2(a):1/0,h=(r.kind===`led`?0:f2(`✕`)+1)+c.reduce((e,t)=>e+f2(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?g2(v.map(e=>e.cellLength),m,h):r2(g.entries,g.groups,i),b=parseInt(P0(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>Ta([{verb:Wi,args:[d,n.key,String(e)]}]),ee=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],te=r.kind===`own`&&r.onPick?ee:[],E=e=>Ta([...B0(l,e,e,u,d,a.signer).effects,...te]),ne=(e,n)=>R0(e,E(t.options[n])),D=r.kind===`led`?[]:[L0(`✕`,Ta(ee),!1,s)];D.push(...c.map(({glyph:e,option:r})=>L0(e,Ta([...B0(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&D.push(L0(`←`,T(C-1),!1));let re=C<y.length-1?[L0(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[_2([...D,...e.map(e=>ne(v[e],e)),...re])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=w.length===1?[new K(`${w[0].label}${O}`,{style:ie})]:[],oe=[_2([...D,...ae,...re])];for(let e of w){w.length>1&&oe.push(_2([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>f2(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:UA(i),o=` `.repeat(n-f2(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(_2([ne(p(r,a2(s,m)),r)]))}}return oe}function x2(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{aU(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=v2(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=y2(e,n,`picker`),u=d2(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=t.drawnAt(),f=t=>b2(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,$0(u,pv(void 0),E0(e,`{{ picker }}`),l.paletteOf,d,t),q0(u.palette,t,d)),p=zv(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function S2(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function C2(e,t,n,r,i){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 a=T0(i,`carousel`).store;if(!a.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 o=i.compiled.get(e),s=F0(i,`carousel`),{options:c}=t;if(c.length===0)return _2([]);let l=S2(c,P0(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ta(B0(o,u(e),u(e),a,s,i.signer).effects);return _2([L0(`◀`,d(-1),!1),R0(t2(E0(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ta(B0(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),L0(`▶`,d(1),!1)])}function w2(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(M0(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return C2(t,y2(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function T2(e,t,n){let r=y2(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 E2(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 D2(e,t,n,r){let i=T2(e,t,n),a=r??P0(T0(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,E0(e,`{{ ${n} }}`))}function O2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(aU(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return X0(D2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function k2(e,t,n){return{swatches:{fn:(r,i)=>{let a=T2(e,r,`swatches`),o=v2(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=d2(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]=b2(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,n2(s,E0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),q0(s.palette,s.bg,c),u===0?[]:(()=>{let t=S2(l,P0(T0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[E2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const A2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function j2(e,t,n,r){let i=zv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:kv(e,n,r)});return[[$_(e,t,r).map((n,i)=>{let a=Dv(e,n);return{text:A2[i%A2.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function M2(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:K0({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 K(e)),r.push(a)}return r}function N2(e,t,n,r,i){let a=j2(e,t,n,r).map(e=>M2(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
480
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
481
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
476
|
+
`}const kQ=e=>({kind:`ok`,value:e}),AQ=e=>({kind:`failed`,reason:e});var jQ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const MQ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function NQ(e){return MQ.test(e)?e:null}function PQ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return kQ(null);let n=t.value;return kQ({app:n,forwarder:e.exists(ws(n))})}async function FQ(e,t){let n=e.monotonic()+5e3;for(;e.monotonic()<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`,delivery:r.delivery}}return null}async function IQ(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(`${Vi}://${fa}/${n}`);return(r===null?await FQ(e,n):null)??{kind:`lost`,unopened:r,opener:PQ(e)}}function LQ(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?kQ(i.stdout):AQ(Ze(i))}const RQ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Vi}://probe"));u.isNil() ? "" : u.path.js`;async function zQ(e){let t=await yQ(e);if(t.kind!==`ok`)return AQ(fr(t).split(`
|
|
477
|
+
`).join(` — `));let n=bQ(t.value,[`handlerProbes`]);if(n!==null)return AQ(n);let r=[];for(let e of t.value.handlerProbes){let t=BQ(e);if(t===null)return AQ(`the daemon lists its probe arrivals without who delivered them, so it is from a build before the forwarder app — restart it to run the installed one`);r.push(t)}return kQ({arrivals:r})}function BQ(e){if(typeof e!=`object`||!e)return null;let{nonce:t,delivery:n}=e;if(typeof t!=`string`||typeof n!=`object`||!n)return null;let{kind:r,urlV:i}=n;return r===`cli`?{nonce:t,delivery:{kind:`cli`}}:r===`forwarder`&&typeof i==`number`?{nonce:t,delivery:{kind:`forwarder`,urlV:i}}:null}function VQ(e,t){let{host:n,clock:r}=t;return{platform:process.platform,sockets:{own:fn(n),handler:pn()},monotonic:()=>r.monotonic(),nonce:le,daemon:()=>zQ(t),open:t=>{let n=LQ(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>Le(r,100),opener:()=>{let t=LQ(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,RQ]);if(t.kind===`failed`)return t;let n=t.value.trim();return kQ(n===``?null:n)},exists:s.existsSync}}const HQ=/^─{20,}/,UQ=/^❯(\s|$)/,WQ=/›\s*stashed$/;function GQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>HQ.test(e)?[t]:[]).at(-2);return n===void 0||!UQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function KQ(e){if(e.inMode)return{kind:`in-mode`};let t=GQ(e);return t===null?{kind:`no-prompt`}:WQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function qQ(e){return/^❯\s*\S/u.test(GQ(e)?.prompt??``)}const JQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function YQ(e){return e.screen.some(e=>JQ.test(e))}const XQ={"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 ZQ(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}}async function QQ(e,t,n){let r=ZQ(t);if(r.kind===`refused`)return r;let i=r.hint,a=KQ(await e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:XQ[a.kind]};let o=await e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}async function $Q(e,t,n,r,i){let a=await pc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function e$(e,t){let n=await $Q(e,t,`claude-input.read`,[`display`,`-p`,`-t`,t.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,t.pane]);if(n.kind===`rate-limited`)throw Error(n.reason);let[r=``,...i]=n.stdout.split(`
|
|
478
|
+
`);return{inMode:r!==`0`,screen:i}}function t$(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`]}async function n$(e,t,n){let r=await $Q(e,t,`claude-input.type`,t$(t.pane,`cc-candybar-slash`,[`C-s`]),n);return r.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${r.reason})`}}function r$(e){return{read:t=>e$(e,t),type:(t,n)=>n$(e,t,n)}}const i$=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function a$(e){let t=eq(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function o$(e){return YG(()=>decodeURIComponent(e))}const s$=5e3;function c$(e,t,n){if(e.reason===`rate-limited`){n(`warn`,Ze(e));return}throw e.reason===`aborted`?new qG(t):Error(`${t} failed (${Ze(e)})`)}async function l$(e,t,n,r){let i=await e.launch({...t,timeoutMs:s$});i.ok||c$(i,n,r)}async function u$(e,t,n,r,i,a){let o=p(E.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:E.join(o,`stderr`),status:E.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){c$({...s,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(s.pid),l=kt(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;c$(l.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:h(a.stderr,`utf8`),exitCode:l.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await Le(e.clock,50)}}finally{_(o,{recursive:!0,force:!0,maxRetries:3})}}function d$(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const f$=(e,t)=>d$(o$(e),t),p$=new Set([`request`,`feed`]);function m$(e){if(!p$.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const h$=async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n),o=t.diagnosticCopy(a,m$(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open the indicator beside the settings door again and copy from there`);await d$(o,t)},g$=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,o$(e)],category:`click.open`},`open -a "Visual Studio Code"`),_$=async(e,t)=>{let n=a$(o$(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},v$=async(e,t)=>{let[n=``,...r]=YG(()=>wa(e)),i=a$(n),a=t.gates.state.gateFor(M$(t,i));if(r.length===0)throw new Z(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Z(`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 Z(`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 Z(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}S$(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},y$=/^-?\d+$/;function b$(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const x$=async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!y$.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=M$(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new Z(`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&&y$.test(u)?C$(l,parseInt(u,10)):w$(`step-state`,r,l,PG(s,e=>t.sessionState.get(a,e),r)),f=b$(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);S$(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function S$(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Hk));if(i.length===0)return;let a=CG(M$(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function C$(e,t){return Math.max(e.min,Math.min(e.max,t))}function w$(e,t,n,r){if(r===null)return n.min;if(!y$.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return C$(n,parseInt(r,10))}function T$(e,t,n){let r=t.get(n,KG);return r===null?e:{...e,target:{source:`pick`,path:r}}}function E$(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function D$(e){let t;try{t=JSON.parse(e)}catch{throw new Z(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Z(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Z(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:E$(a,i)}}function O$(e,t){let n=A$(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function k$(e,t){let n=e.sessionState.get(t,WG);return n===null?null:D$(n)}function A$(e,t){let n=k$(e,t);return n===null?null:T$(n,e.sessionState,t)}function j$(e,t,n){let r=A$(e,t);if(r===null)return;let{path:i}=F$(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function M$(e,t){return e.configFor(O$(e,t))}function N$(e,t){let n=k$(e,t);if(n===null)return null;let r=()=>e.lanes.of(T$(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function P$(e,t){let n=A$(e,t);return n===null?IG:BG(e.configFor(n))}function F$(e,t){return yB(e.locations,tV(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function I$(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const L$=async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n),o=O$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`set-config: ${l.reason}`);let u=F$(t,o),d=xG(s,e=>t.sessionState.get(a,e),r);RK(I$(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},R$=async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!y$.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=O$(t,a),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(r);if(!u)throw new Z(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=F$(t,s),f=xG(c,e=>t.sessionState.get(a,e),r),p=LK(d.path,f.key),m=typeof p==`number`?C$(u,p):w$(`step-config`,r,u,FG(f.globals,r)),h=b$(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);RK(I$(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},z$=async(e,t)=>{let[n=``]=YG(()=>wa(e)),r=a$(n),i=O$(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=yG(a,o),c=SG(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save: ${t.reason}`);return[e.target,t.value]});V$(`save`,l,c);let d=F$(t,i);zK(I$(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.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(B$)].join(` `)} → ${d.path} (session=${r})`)},B$=e=>`${e.preset}/${e.id}.settings.${e.setting}=${lb(e.value)}`;function V$(e,t,n){for(let r of n){let n=t.validate(r.key,lb(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const H$=async(e,t)=>{let[n=``]=YG(()=>wa(e)),r=a$(n),i=O$(t,r),a=t.configFor(i),o=EG(a,e=>t.sessionState.get(r,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save-preset: ${t.reason}`);return[e.configKey,t.value]});V$(`save-preset`,s,o.placements);let l=F$(t,i),u=KK(I$(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Nx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,jx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(B$)].join(` `)} → ${l.path} (session=${r})`)},U$=async(e,t)=>{let[n=``]=YG(()=>wa(e)),r=a$(n),i=O$(t,r),a=OG(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Z(`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=F$(t,i);qK(I$(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(yG(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Tx.map(e=>jx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Tx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},W$=async(e,t)=>{let[n=``,r=``]=YG(()=>wa(e)),i=a$(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=O$(t,i),o=F$(t,a);JK(I$(t,i),o,r),t.reloadConfig(a);let s=jx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},G$=async(e,t)=>{let[n=``,...r]=YG(()=>wa(e)),i=a$(n),a=O$(t,i),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Z(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=F$(t,a),l=r.map(kG),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);UK(I$(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function K$(e,t){let n=(e,t)=>[...Uy(_S(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(mS(t.presets).flatMap(e=>n(t,e).map(t=>Uk(DS(e),zy(t)))));return mS(e.presets).flatMap(t=>n(e,t).map(e=>({member:Uk(DS(t),zy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function q$(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[zk]:[]])}const J$=async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n),o=O$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`apply-layout-op: ${l.reason}`);let u=Zte(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=F$(t,o),f=YK(I$(t,a),d,r,u);t.reloadConfig(o);let p=q$(K$(s,t.configFor(o)),t.sessionState.get(a,zk)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},Y$=async(e,t)=>{let[n=``]=YG(()=>wa(e)),r=a$(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),j$(t,r,i),t.log(`info`,`undo: restored ${Cq(i)} (session=${r})`)},X$=async(e,t)=>{let n=a$(o$(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(M$(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},Z$=async(e,t)=>{let n=a$(o$(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);j$(t,n,r),t.log(`info`,`rewind: put back ${Cq(r)||`nothing`} as edit mode found it (session=${n})`)},Q$=async(e,t)=>{let[n=``]=YG(()=>wa(e)),r=a$(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),j$(t,r,i),t.log(`info`,`redo: re-applied ${Cq(i)} (session=${r})`)},$$=async(e,t)=>{a$(o$(e)),await t.applyUpdate()};function e1(e,t){let n=e.sessionState.get(t,GG);if(n===null)throw new Z(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Z(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Z(`client hints record is not an object: ${n}`);return zn(r)}function t1(e,t,n){let r=$M(n);e.sessionState.setBatch(t,gN(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${rN(n.config)} ${mN(n.nerdFont,n.marks)} ${iN(n.terminal,n.clicked)} ${aN(n.terminal,n.width)} ${oN(n.install)} ${cN(n.daemon)} ${lN(n.data)} ${pN(n.transcripts)} ${uN(n.frames,n.claudeSettings)} ${fN(n.claudeSettings.origin.sources)} (session=${t})`)}async function n1(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await dQ({...n,loadConfig:()=>r},e1(e,t),O$(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:Wq(i,a)},uQ(t,a),LZ(e.doctorStores))}catch(e){throw e instanceof Bq?new Z(e.message):e}let s={facts:o,install:FZ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(O$(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:n1(e,t,n,i)}};return s}const r1=(e,t)=>{let n=RZ(e.doctor);return n1(e,t,n,n.loadConfig(O$(e,t)))};async function i1(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=LZ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:sQ(e.arrival),install:i,clicked:a1(e,o)}}function a1(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?Xj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>Rq(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const o1={gathers:!0,prepare:async(e,t)=>{let n=a$(o$(e)),r=await r1(t,n);return async e=>t1(e,n,await i1(e,n,r))}},s1=async(e,t)=>{let n=NQ(o$(e));if(n===null)throw new Z(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Z(`doctor-probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} delivery=${r.kind}`)},c1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=YG(()=>wa(e)),i=a$(n),a=eN(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await r1(t,i);return async e=>{let t=await i1(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Z(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=fQ(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Z(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${cM(n.fix)} (session=${i})`),t1(e,i,r.value)}}},l1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=YG(()=>wa(e)),a=a$(n),o=eN(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!aM.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${aM.join(` or `)}`);let s=await r1(t,a);return async e=>{let t=await i1(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Z(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>Fq(e,...r));if(c.kind===`failed`)throw new Z(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),t1(e,a,{...t,marks:c})}}},u1=async(e,t)=>{let[n=``,r=``]=YG(()=>wa(e)),i=a$(n),a=Object.values(t.configFor(O$(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Z(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(e1(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Z(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function d1([e=``,t=``,n=``,r=``],i){let a=a$(e),o=O$(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Z(`"${t}" is not a run action this session's config declares`);let l=KF(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Z(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Z(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Z(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],envOverlay:{...Mq({sessionId:a,projectDir:o.projectDir,claudeConfigDir:e1(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const f1=new Map([[Ki,i$(f$)],[Yi,i$(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Z(`load-config: expected <sessionId>/<path> (missing separator)`);let r=a$(YG(()=>decodeURIComponent(e.slice(0,n)))),i=YG(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Z(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Z(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,KG),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,KG,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[qi,i$(g$)],[Wi,i$(v$)],[Gi,i$(x$)],[Xi,i$(L$)],[Zi,i$(R$)],[na,i$(G$)],[Qi,i$(z$)],[$i,i$(H$)],[ea,i$(U$)],[ta,i$(W$)],[ra,i$(J$)],[ia,i$(Y$)],[aa,i$(Q$)],[oa,i$(X$)],[sa,i$(Z$)],[Ji,i$(_$)],[ca,i$($$)],[la,o1],[ua,c1],[da,l1],[fa,i$(s1)],[pa,i$(u1)],[`run`,i$(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=YG(()=>wa(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=d1(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[ma,i$(async(e,t)=>{let[n=``,r=``,i=``,a=``]=YG(()=>wa(e)),o=a$(n),s=i;if(!t.links.verify(rV(o,r,s),a))throw new Z(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=nV(tV(t.stateDir),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(O$(t,o))})],[ha,i$(h$)]]),p1=new Set([Wi,Gi,Xi,Zi,na,Qi,$i,ea,ta,ra,ia,aa,oa,sa,Ji,ca,la,ua,da,pa,`run`,ma,Yi,ha]);function m1(e,t){return h1(e===`dispatch`?Ea(t):[{verb:e,value:t}])}function h1(e){let t=e.find(e=>p1.has(e.verb)),n=t===void 0?``:YG(()=>eee(t.value));return n===``?null:eq(n)}const g1=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function _1(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function v1(e,t){let[n]=Oa(Ea(e)),r=n===void 0?void 0:f1.get(n.verb);return r?.gathers?g1(r,n.value,t):void 0}async function y1(e,t,n){let r=[],i=!1,a=Ea(e),o=h1(a);for(let[e,{verb:o,value:s}]of Oa(a).entries()){let a=f1.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await _1(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof qG)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Z||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&hc(t.sessionState,o.id,r.join(`
|
|
479
|
+
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function b1(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function x1(e,t,n,r){let i=e===null?null:N$(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}b1(e)}),c=[],l=e=>UG(e,e=>P$(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(l$(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed(QQ(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=A$(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}b1(c)}function S1(e,t,n){return async(r,i)=>{let a=m1(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>x1(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const C1=new Map([...[...f1].map(([e,t])=>[e,S1(e,async(e,n)=>t.gathers?g1(t,e,n):void 0,(e,n,r)=>_1(t,e,n,r))]),[Ui,S1(Ui,v1,y1)],[fa,s1]]);Object.freeze([...C1.keys()]);function w1(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>x1(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=HG(P$(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:gi}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function T1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const E1=e=>ko(e);var D1=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,E1(n)||L1(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=E1(n)?null:r.now()}read(){let e=this.cell.get();if(E1(e))throw new cI(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){E1(e)||L1(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},O1=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${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_()}},k1=class{constructor(e){this.deriver=e}read(){return this.deriver()}},A1=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new O1(`Variable "${e}"`,()=>{let e=n();return L1(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},j1=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new k1(()=>{let e=n();return L1(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},M1=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(I1(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=I1(e);F1(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},N1=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new O1(`Variable "${e}"`,()=>I1(t()),F1)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function P1(e){return JSON.stringify(e)}function F1(e,t){return P1(e)===P1(t)}function I1(e){return e.kind===`ok`?{kind:`ok`,value:rI(e.value)}:e}function L1(e,t,n,r){let i=iI(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var R1=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new D1(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new M1(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new N1(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?A1:j1;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new k1(n);let r=new O1(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];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()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof M1))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}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`){let e=t.read();return e.kind===`pending`?e:F(P1(e))}try{return F(String(t.read()))}catch(e){return lI(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):Oo(`unread`)}}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.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof A1||t instanceof N1)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}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}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}};function z1(e){return B1(e,new Set(e.names()),``)}function B1(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!H1(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:U1(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return B1(e,t,a)}})}function V1(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 H1(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function U1(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new cI(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function W1(e){return oe(`sha256`).update(JSON.stringify(G1(e))).digest(`hex`)}function G1(e){return Array.isArray(e)?e.map(G1):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,G1(t)])):e}const K1=e=>({digest:W1(e),identity:e});function q1(e){return ae.createHash(`sha256`).update(e).digest(`hex`)}function J1(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(k(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Y1(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]}"`)}}function X1(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,source:e.regex.source,flags:e.regex.flags};case`json`:return{kind:`json`}}}const Z1={session:()=>{throw new cI(`session_id`,`the view's session has no value yet: no view source is bound`)},read:()=>Oo(`unread`),run:()=>jY,drawnAt:()=>{throw new cI(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},Q1=e=>({kind:`found`,value:e});function $1(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&ko(n))return n;if(typeof n!=`object`||!n)return Q1(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&ko(n)?n:Q1(n)}function e0(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the config declares`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function t0(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`?aI(e):t===`number`?oI(e):sI(e)}function n0(e){return e===`number`?0:e===`boolean`?!1:``}var r0=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];runs=X.observable.map(void 0,{deep:!1});runSourcesNow=(0,X.computed)(()=>new Map([...this.runs].map(([e,t])=>[e,t.get()])));namedNow=(0,X.computed)(()=>new Map([...this.runSourcesNow.get()].flatMap(([e,t])=>t.kind===`ok`?[[e,t.value]]:[])));runSources(){return this.runSourcesNow.get()}namedRuns(){return this.namedNow.get()}subscriptionsNow=(0,X.computed)(()=>[...new Map([...this.namedNow.get().values()].map(e=>[e.digest,e]))].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e));subscriptions(){return this.subscriptionsNow.get()}inputs=X.observable.box(Z1,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=wU({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i={}){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.env=i,this.sessionState=n,this.cleanups.push((0,X.observe)(this.subscriptionsNow,()=>{}))}view(){return new e(new R1(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this,this.env)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,iI(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>e0(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new cI(e,`variable "${e}" has no value yet: its source has not answered`);let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=t0(a,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=this.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,{kind:`shell`,command:t,cwd:n.cwd},J1(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r),a=this.registerCachePolicy(e,n),o=(0,X.computed)(()=>{let e=a();return e.kind===`ok`?F(K1({read:t,parse:X1(r),refresh:e.value})):e},{equals:(e,t)=>e.kind===`ok`&&t.kind===`ok`?e.value.digest===t.value.digest:e.kind===t.kind});(0,X.runInAction)(()=>{this.sourceNames.push(e),this.runs.set(e,o)}),this.cleanups.push((0,X.reaction)(()=>this.runFact(e)?.reading,e=>{if(e===void 0||e.kind===`pending`)return;let{at:t,...n}=e;i(n)},{fireImmediately:!0}))}runFact(e){let t=this.runs.get(e)?.get();return t?.kind===`ok`?this.inputs.get().run(t.value.digest):void 0}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,Eo(t,n))}}documentPublisher(e,t){let n=t===void 0?Oo(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(z1(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=t0(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=lI(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}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`,()=>{let e=n.get(this.session(),t.key);return e===null?r:e})}stateRevision(){return this.sessionState===void 0?0:this.sessionState.revision(this.session())}session(){return this.inputs.get().session()}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.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 new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.store.dispose()}registerCachePolicy(e,t){switch(t.kind){case`never`:return()=>F({kind:`never`});case`ttl`:return()=>F({kind:`ttl`,durationMs:t.durationMs});case`watch_file`:return this.cleanups.push((0,X.reaction)(()=>this.runFact(e)?.fault??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0})),()=>F({kind:`watch_file`,path:t.path});case`key`:{let n=this.engine.parse(t.template);return this.answeredUnder(e,()=>{try{return F(n.evaluate(z1(this.store)).map(e=>e.plain).join(``))}catch(e){return lI(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):Oo(`unread`)}})}case`depends_on`:return this.answeredUnder(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?F(e.map(e=>e.value).join(`,`)):Oo(`unread`)})}}answeredUnder(e,t){let n=(0,X.computed)(t,{equals:X.compareStructural});this.cleanups.push((0,X.reaction)(()=>n.get(),t=>this.notePolicy(e,t),{fireImmediately:!0}));let r;return()=>{let e=n.get();return e.kind===`ok`&&(r=e.value),r===void 0?e.kind===`failed`?e:Oo(`unread`):F({kind:`key`,hash:q1(r)})}}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return t0(this.defaultEmptyValue,t)}catch{return n0(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.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 i0(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const a0={kind:`hidden`},o0={kind:`shown`};function s0(e,t){try{return i0(e,t)?o0:a0}catch(e){let t=lI(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function c0(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function l0(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function u0({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function d0({text:e,placement:t,lead:n,trail:r}){return{text:f0(e),placement:t,...n!==void 0&&{lead:f0(n)},...r!==void 0&&{trail:f0(r)}}}function f0(e){let t=e.blankCopy(e.plain);t.style=xA(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(xA(i).clearMetaAndLinks(),n,r);return t}function p0(e){let t=u0(e);if(t.length===1)return e.text;let n=c0(t);return n.style=e.text.style,n}function m0(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=c0(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:c0([d,...c],a)},...l.length>0&&{trail:c0([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(l0(u,n,p),[{text:u,...f}])}function h0(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return wj(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function g0(e,t){if(e.length===0)return 0;let{lines:n}=Tj(e.map(({owner:e})=>e),t),r=z(uj(n[n.length-1]));return Math.max(0,r-vj(t)+yj(t))}function _0(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=Tj([e],{...n,width:1/0});return z(uj(r.flat()))<=n.width}function v0(e,t,n,r){if(_0(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=g0(n,r);return i.divide(h0(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function y0(e,t){let n=Math.max(2,Cj(t)-vj(t)-t.padding);return b0(e,t).reduce((e,r)=>[...e,...v0(r,n,e,t)],[])}function b0(e,t){let n=()=>e.map(e=>({owner:p0(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=Tj(e.map(p0),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(uj(i.flat()))),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];l0(c,c.cellLength+a,n)}),n()}function x0(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=S0(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:xA(a.style)};if(e.style.link){i();let r=S0([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function S0(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>C0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function C0(e,t){let n=e.copy();return n.style=t,n}function w0(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 T0(e,t){let{look:n}=w0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function E0(e,t){let{layout:n}=w0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function D0(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 O0(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,k0(e,t,o,n,r,i));return i}function k0(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=TS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,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=Ix.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=TS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,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=TS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:M0(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:M0(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(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:KF(n),argv:n.run.map(n=>M0(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,M0(e,r,t)])};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:M0(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 A0(e){return e.kind===`do`?A0(e.head):e}function j0(e){switch(A0(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`slash`:case`run`:case`do`:return!1}}function M0(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function N0(e,t){return e.has(t)?aI(e.read(t)):``}function P0(e,t){return w0(e,t).registry.session()}function F0(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function I0(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function L0(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([xA(e.style),r])});for(let t of e.spans)i.stylize(U.combine([xA(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function R0(e,t){return Math.max(e.members.indexOf(N0(t,e.stateVar)),0)}function z0(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=N0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=N0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=N0(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(R0(e,r)+1)%e.members.length];return{effects:[{verb:Wi,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Gi,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ki,args:[F0(e.text,z1(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[F0(e.target,z1(r))]}],active:!1};case`persist-literal`:{let t=N0(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=N0(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(R0(e,r)+1)%e.members.length];return{effects:[{verb:Xi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Zi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:na,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`redo`:return{effects:[{verb:aa,args:[i]}],active:!1};case`back`:return{effects:[{verb:oa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:sa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:ea,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ta,args:[i,F0(e.name,z1(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:la,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ua,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:da,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:pa,args:[i,e.line]}],active:!1};case`run`:{let t=z1(r),n=JSON.stringify({run:e.argv.map(e=>F0(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,F0(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:ra,args:[i,e.key,CF(e.op)]}],active:!1};case`do`:{let o=z0(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>z0(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:ra,args:[i,e.key,CF(r)]}],active:!1}}}}function B0(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:bi(`action "${e}"`,n,t.members.length,R0(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 V0(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=w0(n,`action "${e}"`).store,{display:a,boundValue:o}=B0(e,A0(r),t,i),s=P0(n,`action "${e}"`),{effects:c,active:l}=z0(r,a.plain,o,i,s,n.signer);return L0(a,Ta(c),l)}function H0(e){return{action:{fn:(t,...n)=>V0(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function U0(e,t){return I0(`✕`,Ta([{verb:Wi,args:[e,t,gi]}]),!1)}function W0(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(kv(e,t,n))})}function G0({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function K0(e,t,n){return new U({color:H.fromRgba(Uu(e.get(`warning`),t,Ov,n))})}function q0(e,t,n){return U.combine([W0(e,t,n),K0(e,t,n)])}function J0(e,t,n){return G0(Bv(e.palette,e.disclosure,t,n))}function Y0(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(j_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const X0=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},Z0=e=>new U({bold:e});function Q0(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>X0(a,U.combine([J0(e,{...n,distribution:t},i),Z0(o)]));let o=W0(e.palette,a,i);return(e,t,i,a)=>$0(i,U.combine([o,Z0(a)]),r(t,n))}const $0=(e,t,n)=>X0(K.fromFragments([X0(e,t),X0(` `,t),Y0(n)]));function e2(e,t,n,r){return t===void 0?X0(r):$0(r,void 0,t(n,e))}function t2(e,t,n,r,i){let a=W0(e.palette,i,r);return(e,r,i,o)=>X0(K.fromFragments([X0(o?`[`:` `,a),Y0(n(r,t)),X0(o?`]`:` `,a)]))}function n2(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=>r2(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function r2(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function i2(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function a2(e){return{current:null,drawnAt:e}}function o2(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 s2(e,t,n){return l2(e,()=>n(o2(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function c2(e,t){return l2(e,()=>(e.current=null,t()))}function l2(e,t){let n=e.current;try{return t()}finally{e.current=n}}function u2(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 d2(e){return new K(e).cellLength}function f2(e){let{width:t,chromeCols:n,padding:r}=w0(e,`a row fit`);return Math.max(1,t-n-2*r)}function p2(e){let{padding:t,seamCols:n}=w0(e,`a row fit`);return Math.max(1,f2(e)-(d2(`✕`)+2*t+n))}function m2(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 h2(e,t,n){let r=d2(`←`)+1+d2(`→`)+1,i=m2(e,t,n);return(i.length>1?m2(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function g2(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function _2(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 v2(e,t,n){let r=e.compiled.get(t),i=r&&A0(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 y2(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=w0(a,`picker`).store,d=P0(a,`picker`),f=`stateVar`in t?N0(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`?p2(a):f2(a):1/0,h=(r.kind===`led`?0:d2(`✕`)+1)+c.reduce((e,t)=>e+d2(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?h2(v.map(e=>e.cellLength),m,h):n2(g.entries,g.groups,i),b=parseInt(N0(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>Ta([{verb:Wi,args:[d,n.key,String(e)]}]),ee=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],te=r.kind===`own`&&r.onPick?ee:[],E=e=>Ta([...z0(l,e,e,u,d,a.signer).effects,...te]),ne=(e,n)=>L0(e,E(t.options[n])),D=r.kind===`led`?[]:[I0(`✕`,Ta(ee),!1,s)];D.push(...c.map(({glyph:e,option:r})=>I0(e,Ta([...z0(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&D.push(I0(`←`,T(C-1),!1));let re=C<y.length-1?[I0(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[g2([...D,...e.map(e=>ne(v[e],e)),...re])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=w.length===1?[new K(`${w[0].label}${O}`,{style:ie})]:[],oe=[g2([...D,...ae,...re])];for(let e of w){w.length>1&&oe.push(g2([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>d2(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:UA(i),o=` `.repeat(n-d2(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(g2([ne(p(r,i2(s,m)),r)]))}}return oe}function b2(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{iU(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=_2(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=v2(e,n,`picker`),u=u2(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=t.drawnAt(),f=t=>y2(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,Q0(u,pv(void 0),T0(e,`{{ picker }}`),l.paletteOf,d,t),K0(u.palette,t,d)),p=Rv(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function x2(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function S2(e,t,n,r,i){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 a=w0(i,`carousel`).store;if(!a.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 o=i.compiled.get(e),s=P0(i,`carousel`),{options:c}=t;if(c.length===0)return g2([]);let l=x2(c,N0(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ta(z0(o,u(e),u(e),a,s,i.signer).effects);return g2([I0(`◀`,d(-1),!1),L0(e2(T0(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ta(z0(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),I0(`▶`,d(1),!1)])}function C2(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(j0(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return S2(t,v2(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function w2(e,t,n){let r=v2(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 T2(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 E2(e,t,n,r){let i=w2(e,t,n),a=r??N0(w0(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,T0(e,`{{ ${n} }}`))}function D2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(iU(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return Y0(E2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function O2(e,t,n){return{swatches:{fn:(r,i)=>{let a=w2(e,r,`swatches`),o=_2(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=u2(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]=y2(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,t2(s,T0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),K0(s.palette,s.bg,c),u===0?[]:(()=>{let t=x2(l,N0(w0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[T2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const k2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function A2(e,t,n,r){let i=Rv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:kv(e,n,r)});return[[$_(e,t,r).map((n,i)=>{let a=Dv(e,n);return{text:k2[i%k2.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function j2(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:G0({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 K(e)),r.push(a)}return r}function M2(e,t,n,r,i){let a=A2(e,t,n,r).map(e=>j2(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
480
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function N2(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(iU(`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}=T0(e,`{{ themePreview }}`);return M2(r===void 0?a:E2(e,r,`themePreview`),o,{...u2(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),p2(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const P2=e=>e.slice(e.lastIndexOf(`.`)+1),F2=(e,t)=>{let n=new K(P2(e));return n.truncate(t,{marker:`…`}),n.plain};function I2(e,t){let n=e.map(e=>e.map(({name:e})=>d2(P2(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 L2(e,t,n,r){let i=I2(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new K(` ${F2(s,i)} `,{style:G0(Xv(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
481
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const R2=`layoutPreview`;function z2(e,t){return{[R2]:{fn:()=>L2(E0(e,`{{ layoutPreview }}`),T0(e,`{{ layoutPreview }}`).decor,t.drawnAt(),p2(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function B2(e,t,n,r){let i=u2(r.activeSegment,`{{ menu }}`),a=r.action,o=kS(i.placementId,e,n.key),s=MS(o),c=OS(e),l=w0(a,`menu`).store,u=N0(l,o)===c,d=P0(a,`menu`),f=u?gi:c,p=I0(bi(`{{ menu "${e}" }}`,t,2,+!!u),Ta([{verb:Wi,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=Rv(i.palette,i.disclosure,t).plane,l=v2(a,e,`menu`);return y2(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,gi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,Q0(i,n.distribution,T0(a,`{{ menu }}`),l.paletteOf,t,c),K0(i.palette,c,t))})():[]),p}const V2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function H2(e,t){let n=t[t.length-1],r=V2(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:IS(r??{})}}function U2(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=H2(t,n);return B2(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function W2(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=G2(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 K(t?i:a,{style:l===void 0?void 0:new U({color:l})}))}let l=K.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function G2(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 K2(e){let t={fn:(()=>{let t=u2(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:(()=>u2(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=u2(e,`{{ roleTextOn }}`);return Y2(r,t,Fu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=u2(e,`{{ keptOn }}`),i=Fu(r,t),a=Fu(r,n),o=xl(Gu(i,V.TRUECOLOR),Gu(a,V.TRUECOLOR)),s=Math.min(Ov,o),c=e.drawnAt(),l=Wu(i,c,(e,t)=>xl(e,t(a))>=s);if(l===void 0)throw Error(`keptOn: nothing drawn at ${V[c]} stands ${s.toFixed(2)}:1 off ${a.hex} (drawn ${Gu(a,c).hex})`);return l.hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=zH(()=>u2(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...X2(s)];return W2({value:e,max:t,width:n,filled:r,empty:i,colourAt:c===void 0?void 0:e=>String(a.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...a,bgOf:t,tint:n,roleTextOn:r,keptOn:i,gauge:o}}const q2={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},J2=Object.values(q2).flat();function Y2(e,t,n){let r=Gu(n,V.TRUECOLOR),i=t=>{let n=Fu(e,t);return{colour:n,ratio:xl(Gu(n,V.TRUECOLOR),r)}},a=Hu(r).hex,o=q2[a];if(o===void 0)throw Error(`contrastFor named ${a} for ${n.hex}, which is neither pole`);let s=`text-${t}`,c=e=>`${t}-${e}`,l=new Map([s,t,...J2.map(c)].map(e=>[e,i(e)]));return([s,t,...o.map(c)].map(e=>l.get(e)).find(({ratio:e})=>e>=4.5)??[...l.values()].reduce((e,t)=>t.ratio>e.ratio?t:e)).colour}function X2(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)]})}const Z2={input:`view`,state:`view`,template:`view`,time:`view`,source:`view`,shell:`view`,file:`view`,literal:`directory`,env:`directory`,dropped:`directory`},Q2=new WeakMap;function $2(e){let t=Q2.get(e);return t===void 0&&(t=new Map([...YR(e)].map(([e,t])=>[e,Z2[t.kind]])),Q2.set(e,t)),t}function e4(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
482
482
|
`)){n.push(r);continue}let e=r.split(`
|
|
483
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function n4(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}`}})}const r4=e=>e.kind===`failed`?o0:e;function i4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function a4(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:n,opened:r.length>0,ground:i},deeper:r}}function o4(e){return{...e,cells:e.cells.map(f0)}}function s4(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,...c4(e,r)]}function c4(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 l4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:s4(e.direction,e.children.map((t,i)=>n(t,[...r,u4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function u4(e,t){return e.steps[t]}function d4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=f4(e);return{width:p4(t),reach:m4(t)}}function f4(e){let t=e.children.map(d4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const p4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),m4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function h4(e,t){let n=f4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=zy[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),m4(n),p4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const g4={compile(e,t){let n=h4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Gy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),s4(e.direction,e.children.map((n,r)=>t.renderChild(n,r4(t.gate),u4(e,r))))}},_4={drop:e=>e.place,above:()=>`above`},v4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},y4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:By(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ky(t.path),void 0),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,b4(e,t))};function b4(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=H1(t.scope,e.settings);if(t.gate.kind===`failed`)return E4(e,r,t,t.gate.message);try{let i=t.placement(e),a=i4(t.gate,i.gate());if(a.kind===`failed`)return E4(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return E4(e,r,t,s.message);let c=Ux(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:$k(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?x4(f.variable):S4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?C4(p.segment,u):w4(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:o0,h.disclosure).map(e=>({...e,place:_4[v.placement](e)})),b=(e,t,n)=>h0(S0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?v4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new K(` `.repeat(T4(d0(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],ee=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(d0)),[...te,...ee]}catch(n){return E4(e,r,t,n.message??String(n))}}const x4=e=>({kind:`waiting`,variable:e});function S4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=uI(e);if(t===void 0)throw e;return x4(t.variable)}}function C4(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:t4(S0(r,c)).map((e,t)=>({cells:h0(e,{...l,lead:t===0?S0(i,c):[],trail:t===0?S0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:h0(S0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function w4(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=S0(D4(e.lead,e,t,n),l),d=S0(D4(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return h0(S0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function T4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function E4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:h0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:$k(n.palette)},lead:D4(e.lead,e,t,n),trail:D4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function D4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=uI(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const O4={container:g4,segment:y4};function k4(e){return O4[e]}var A4=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?j4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const j4={kind:`hidden`},M4={palette:`theme`,style:`style`,effect:`effect`},N4=Lx.get(`colorCompatibility`),P4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function F4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function I4(e){if(e.ok)return e.value;throw e.error}const L4=e=>({read:()=>e}),R4=k_({basePalette:O_,palette:O_,decor:Wv});var z4=class{evaluated=0;memory=new A4;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&R4(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=B1(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(N4);return e.kind===`found`&&typeof e.value==`string`&&Oy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(P4,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return l4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=vF(e);return i===void 0?[]:[{name:i,address:n,palette:Ux(r.theme,t)}]}))}),t.bindInputs({session:()=>this.view.get().session,read:e=>this.inputAt(e),run:e=>this.view.get().run(e),drawnAt:()=>ky(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=jk(e);return t===void 0?kk(e)===void 0?e0(this.view.get().payload(),e):e0(this.projected,e):$1(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[M4[e]];if(t.kind===`decided`)return H4(t.name,null,null);let r=W4(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=G4(this.source,e,i.name,r.where,e=>{t=e}),H4(n,t,null)}case`pending`:return H4(n??hy[e],null,i.variable);case`failed`:return n=hy[e],H4(n,gy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!U4(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??hy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return c0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>l2(this.source.activeSegment,()=>c0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new K4(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:O0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=uI(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:F4(e)}),I4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:vF(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function B4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new z4(t,n,e,r);return e.views.set(t,a),a}function V4(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const H4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),U4=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function W4(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 view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function G4(e,t,n,r,i){switch(t){case`palette`:return Jx(n,r,i).name;case`style`:return fy(n,e.styles).name;case`effect`:return Sy(n).name}}var K4=class{where=q4(k_({palette:O_,region:Hv}));ground=q4(k_({colours:Y4,bodyOpen:O_}));opened=q4(k_({colours:Y4,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=H1(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?L4(s0):e.derive(`${t.id} when`,e.readsInstant(a),()=>l2(r,()=>c0(a,i))),this.open=d===void 0?L4(o0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>l2(r,()=>c0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return Q4(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return $4(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?L4(t3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return e3(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),r3(n,r,this.affixes.read())}};function q4(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const J4=(e,t)=>e.hex===t.hex,Y4=k_({palette:O_,drawnAt:O_,tint:J4,text:J4,bg:J4,disclosure:Gv});function X4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const Z4=e=>zv(e.palette,e.disclosure,e.drawnAt);function Q4(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Zv(n,r,i)};return c2(e,X4(t,c),e=>{let t=tA(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function $4(e,t,n,r,i,a){return c2(e,X4(t,n),e=>(e.bg=i?Z4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function e3(e,t,n,r,i,a,o){return c2(e,X4(t,n),e=>(e.bg=r?Z4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const t3={lead:[],trail:[],drops:[]};function n3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return G0(t,Z4(e).state,n)},get band(){return G0(t,Z4(e).plane,n)},get close(){return J0(t,Z4(e).state,n)},disclosure:r}}function r3(e,t,n){return{styles:n3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function i3(e,t,n,r,i,a,o){let s=Q4(e,t,n,r,i,void 0,void 0,o);return r3(s,$4(e,t,s,a,!1,o),t3)}function a3(e,t,n,r,i){return n3(Q4(e,t,n,r,i,void 0,void 0,{}))}function o3(e,t,n,r){return{session:n,payload:()=>e,run:r,selections:()=>t}}function s3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:X1(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 c3(e,t){switch(Yy(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 l3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:s3(n.cache),parse:c3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:s3(n.cache),parse:c3(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function u3(e,t,n,r=hw.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function d3(e,t,n){let{compiled:r,loadWarnings:i}=p3(e,t,n.cwd,f3(n.signer),_3);return{...r,loadWarnings:i}}const f3=e=>(t,n)=>v3(n,e);function p3(e,t,n,r,i=_3){let a=m3(e),o=h3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:g3(e,t,n,i)}}function m3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Rx)n in t&&r.set(e,n);for(let[t,n]of nb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...NU(e)].sort(([e],[t])=>e<t?-1:1)}}function h3(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function g3(e,t,n,r){let i=e4(e),a=NU(e),o=[];for(let[s,c]of XR(e))if(r.has(i.get(s)))try{l3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const _3=new Set([`directory`,`view`]);function v3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>T0(i,`drawnAt`).registry.drawnAt(),o=o2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=hS(e.presets),u=fF(e),d=[e=>k2(i,o,e.now)],f=TU({extraFuncs:{...U0(i),...O2(i),...x2(i,o),...w2(i),...P2(i,o),...B2(i,o),...W2(s),...q2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=u3(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=k0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:u3(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=ob(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Eee(t,e,a,t=>String(T0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return k4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=vS(e,t);C.set(t,S(n,r,void 0))}let w=new Map(sy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of FU(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:x3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),ee={reads:EU({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:CU(d)},te=RU(ee),E=[...C.values()].flatMap(b3(y)).some(e=>te(m.get(e))),ne=E?new Set([...ee.clock,z2]):ee.clock,D=RU({...ee,clock:ne}),re=new Set([...m].flatMap(([e,t])=>D(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=RU({reads:EU({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:ee.projections,clock:ne});for(let e of Cz){let n=y[t][e];n!==void 0&&r(m.get(n))&&re.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,instant:re,layoutReadsInstant:E,styles:e.styles,runtime:i,views:new WeakMap}}function y3(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const b3=e=>t=>{let n=[];return l4(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function x3(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const S3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function C3(e,t,n,r,i){let a=w3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function w3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??hy[e];case`failed`:return r({kind:`rule`,slot:e,message:gy(t.where,e,`the rule failed — ${n.error}`)}),hy[e]}}function T3(e){return E3(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function E3(e){return e.kind===`container`?e.children.flatMap(E3):[e,...e.opens===void 0?[]:E3(e.opens.body)]}function D3(e,t,n,r,i,a,o,s){let c={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return B4(e,t,n,o3(c,a,o,s)),c}function O3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new NA(``),h=m.clockAt(a,vy[c.animationSpeed]),g=l.u(pU(a,h.timeline)),_=V4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:vj(v),padding:v.padding,seamCols:yj(v),preset:c.preset},i);let y=_.evaluated;l.u(O0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,a4),T=_.memory.from(C),ee=new Set,te={held:e=>T?.rules.get(e),waited:e=>ee.add(e),settled:w.rule},E=new Map,ne=e=>{let n=_.slot(e);if(E.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&ee.add(n.waited),n.name;let r=G4(t,e,C3(e,n.rule,_,p,te),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:D,style:re,effect:ie}=_.selections(),O=D.kind===`decided`?D:Jx(ne(`palette`),``,S3),ae=re.kind===`decided`?re:fy(ne(`style`),e.styles),oe=ie.kind===`decided`?ie:Sy(ne(`effect`)),se=O.value,ce=Gx(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:T,returned:a4,hold:o4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,n,i)=>{let a=n.kind===`hidden`?n:i4(n,_.gate(e)),o=a.kind===`failed`?{...a,report:()=>{let t=`when over ${T3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:a.message,message:`${t}: ${a.message} — what it gates is hidden`})}}:a,s={scope:_.scope,palette:ce,gate:o,padding:v.padding,region:i,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,a,o)=>i3(t.activeSegment,e,a,i,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Yv(i,n)),renderBody:(e,t,n)=>pe(e,t,Xv(n)),closeDisclosure:e=>W0(r.session(),e),placed:(e,t)=>w.placed(e,de.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>ee.add(e),decorations:(e,n)=>a3(t.activeSegment,e,n,i,r.drawnAt())};return k4(e.kind).render(e,s)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${pS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=n4(pe(me,s0,Jv(S))).map(({line:e,row:t})=>{let n=b0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...Tj(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),w.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||E3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...ee].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:E}}catch(e){l.e=e}finally{l.d()}}const k3={moving:1e3/30,still:1e3},A3=[`data`,`state`,`reload`,`visibility`];function j3(e){return Wb.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 M3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const N3=(e,t)=>Ub[t].handsOff?e.resp:e.statusline,P3=e=>Math.round(1e3/e);var F3=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++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}feedOpen(e){return this.feeds.has(e)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}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}latest(e){return this.requests.get(e)?.req??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,t){let n=this.feeds.get(e);if(n===void 0)return Wee;let r=t-1,i=this.shown(n);return Xb(e=>{let a=n.rates.get(e);if(a===void 0)return Jb;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}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.clock.monotonic(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&e.phase.clear(),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.clock.monotonic(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${x(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,P3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}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,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||N3(a,t)!==N3(i,t))&&M3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=N3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}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:tC(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=uY.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);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(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} ceiling=${P3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${A3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function I3(e,t){return Wb.filter(n=>e[n]&&Ub[n].handsOff&&t.has(n))}function L3(e,t){return{severity:AB,lines:[[MB(`[⟲ claude]`,Ta([{verb:na,args:[e,...t.map(e=>Ub[e].switch.setting)]}]))]]}}function R3(e,t){for(let n of Object.entries(t))e.push(n)}const z3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function B3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,x(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function V3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...B3(n)];return{level:z3[n.kind],line:bc(e,i)}}const H3=()=>{},U3=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),W3={ansi:e=>({ok:!0,output:sj(e)}),frame:e=>({ok:!0,frame:e})};function G3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=jo();let i=c.u(t6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=r6(e,i,{by:`feed`,fps:n}),p=W3.ansi(o.body),m=u6(t,o,I3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:W3.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=V3(`render`,s,{kind:`threw`,error:e},A(i,o)),r=U3(e);return{bar:ZA(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:H3,failure:{level:t,line:`frame ${n}`}}}}function K3(e,t,n){let{sessionState:r}=e;return lG(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function q3(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:oG(i.view.source.effective(),Tc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function J3(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return oG(K3(e,n,o.state),s===null||Tc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function Y3(e,t,n){R3(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;R3(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:Bn(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const X3=e=>Vn(Bn(e,e.hints));function Z3(e,t,n,r,i){Y3(t,r,i),R3(i,{encoding:t.encoding}),(0,X.runInAction)(()=>{i6(e,t),e.worldStates.take(n),$3(e,t)[Symbol.dispose]()})}function Q3(e,t){(0,X.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function $3(e,t){let n=E$(t.requested,e.sessionState,t.hookData.session_id);return e.renderCache.holdSession(n.projectDir,n.cwd,n.target.path,t)}function e6(e,t,n,r){let i=X3(t);return n6(e,$3(e,t),t,i,n,r)}function t6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{Y3(o,n,r),s=X3(o)}catch(e){throw a[Symbol.dispose](),e}return n6(e,a,o,s,n,r)}function n6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{hints:l}=n,u={hookData:n.hookData,deps:o,cwd:n.cwd,hints:l};return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:s,view:c,hintsError:r,payloadInputs:u,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function r6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.payload(),C=b.source.effective(),w=b.source.failure(),T=oG(C,S.tmux!==void 0);R3(g,{lanes:Wb.filter(e=>T[e]).join(`,`)||`-`});let ee=b.source.hints(),te=S.term.cols;R3(g,{width:String(te)});let E=_c(r,_,h,n.by),ne=E.kind===`held`||E.kind===`owed`?E.error:null,D=o.notice({sessionId:_,dismissed:r.get(_,VF),enabled:C.updateNotice}),re=aV(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Un(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(ne?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:uV(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...Bc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...w===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${w}`}]],de={config:y.config},fe=NB(_,n.by,ae,[...D.offer,...re],[...D.failure,...ue.map(e=>({about:e.kind,text:e.message,copy:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),pe=b.source.facts(),me={diagnostics:UB(fe),drawing:n,feeds:i.feedsOf(_,h),today:AX(pe.builtins.today,h)},he=ko(S.metrics)?void 0:S.metrics;R3(g,EX([...b.state.sources.keys()],b.registry.runSources(),pe)),R3(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:iX(S.git),feeds:j3(me.feeds)});let ge=[],_e=tX(C,te),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=O3(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:ye}),we=FB(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te);f.observe(_,h,be.rows.some(e=>e.kind===`menu`),C.menuTimeout);let De=f.since(_,h);R3(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:te,rows:GB(ee.termRows,n.by===`feed`?Wb.flatMap(e=>{let t=Ub[e].rows;return T[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=WB(r.get(_,Bi),fe),je=Ae===null?be:YA(be,KB(fe,Ae,_,n.by,ke)),Me=u.gitProvider.getStats(),k=u.usageStore.getStats(),Ne=ve.lastFrame(),Pe=Ne.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Fe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,A=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ie=[...D.failure.map(()=>`update-failed`),...[...ue,...ge].map(A)].join(`,`)||`-`;return R3(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${k.size}/${k.hits}h/${k.misses}m`,effect:Ne.effect,effectT:Ne.t.toFixed(3),speed:`${Ne.speed}x`,effectRows:`${Ne.made}made/${Ne.reused}reused`,effectOwn:Pe,fadeBasis:Ne.basis,stateRev:String(Ne.revision),fades:Fe(Ne.fades),leaves:Fe(Ne.leaves),motion:je.motion,evaluated:String(xe),cellBreaks:String(Se),pending:je.pending.join(`,`)||`-`,rules:[...Ce].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:E.kind===`none`?`-`:E.kind,pipeEvent:ce?.hold??`-`,upd:String(D.offer.length),ask:String(re.length),warn:Ie,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:xe,cellBreaks:Se,clickShown:ne,pipeShown:le,delivered:Ee,lanes:T}}function i6(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,KG,o);let s=E1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,GG,s)}function a6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(o6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function o6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:E$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:Oj(t.hookData)}}function s6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:o6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function c6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(e6(e,t,n,i));a6(e,t,oG(l.view.source.effective(),Tc(t.hints.tmux)));let u=o.monotonic(),d=r-u;R3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await IJ(t=>xX(l.payloadInputs,n,f,()=>e.worldStates.of(l.sessionId),()=>l.view.registry.namedRuns().values(),t),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();R3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:fX(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=r6(e,l,Kb),b=t.hookData.session_id,S=I3(y,s.following(b)),C=Aj(t.hints.client??null)===`statusline`,w=C?u6(b,h,S):h.body;return R3(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{frame:w,delivered:l6(e,b,v,g,_)}}catch(e){a.e=e}finally{a.d()}}function l6(e,t,n,r,i){return()=>{n(),r!==null&&pee(e.sessionState,t,r),i!==null&&e.launcher.answeredPipeEvent(i)}}function u6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:YA(t.body,qB(L3(e,[r,...i]),t.diagnostics,e,t.geometry))}const d6=e=>{};function f6(e,t,n=``){let r=U3(t);return{outcome:{kind:`threw`,error:t},resp:{...r,error:`renderer ${e.name}: ${n}${r.error}`},seen:`failed`,settled:d6}}function p6(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&E.isAbsolute(t)&&{location:tB(t)}}}}function m6(e,t){e.push(...t.kind===`answered`?t.output.record:t.record)}async function h6(e,t,n,r,i,a,o,s){let c=p6(r),l=(t,r)=>void e.deliver({kind:`event`,at:Ue(n),event:{kind:`effect-done`,of:t.id,outcome:r===null?{kind:`ok`}:{kind:`failed`,reason:r}}},[[`sid`,c.hookData.session_id],[`effect`,String(t.id)]]),u=await e.answer({kind:`event`,at:a,event:{kind:`config`,context:c,worldState:t.requested(c)}});if(m6(s,u),u.kind===`threw`)return R3(s,{renderer:e.name}),f6(e,u.error,`its config turn: `);let d=await e.answer({kind:`event`,at:a,event:{kind:`request`,id:i,context:c,waitEndsAt:o}});if(m6(s,d),d.kind===`threw`)return R3(s,{renderer:e.name}),f6(e,d.error);let{effects:f}=d.output;R3(s,{renderer:e.name,effects:f.map(e=>`${e.kind}:${e.surface}`).join(`,`)||`-`});let p=null;for(let e of f)switch(e.kind){case`present`:e.request===i?p===null?p=e:l(e,`a second statusline frame for request ${i}`):l(e,`presents request ${e.request}, not this turn's ${i}`);break}if(p===null)return f6(e,Error(`presented no statusline frame for request ${i}`));let m=p,h=n.monotonic(),g;try{g=W3[c.encoding](m.frame)}catch(t){return l(m,`encoding its frame threw: ${U3(t).error}`),f6(e,t,`its frame could not be encoded: `)}return R3(s,{encoded:`${A(n,h)}ms`}),{outcome:{kind:`ok`},resp:g,seen:m.frame.motion,settled:e=>l(m,e?null:`the client did not take the answer`)}}const g6=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`]),_6=[[`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`]],v6=[[`workspace.added_dirs`,`string-list`]];function y6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of _6){let i=S6(n,e);if(i==null)t.missingRequired.push(e);else{let n=b6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of v6){let i=S6(n,e),a=i===void 0?r:x6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))g6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function b6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function x6(e){return Array.isArray(e)&&e.every(e=>b6(e)===`string`)?`string-list`:b6(e)}function S6(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 C6(e,t,n){let{tokens:r}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&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:mA(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function w6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ln.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ln.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function T6(e,t,n,r){let{report:i}=y6(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=tq(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!re(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=w6(e.encoding);s.ok||a.push(s.problem);let c=pr(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=zn(e),{configFile:u,refusedArgs:d}=C6(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:Mj(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:_A(u,l.configEnv)},refusedArgs:d}}}function E6(e,t){switch(e){case`vars`:return{what:e,vars:D6(t)};case`segments`:return{what:e,segments:M6(t)};case`config`:return{what:e,config:I6(t)}}}function D6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=A6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=O6(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:k6(r.lastUpdatedMs(),t.clock)})}return o}function O6(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};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`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function k6(e,t){return e===null?null:Math.max(0,t.now()-e)}function A6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,j6(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}`,j6(i));return t}function j6(e){return e.kind}function M6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=P6(n),o=N6(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:F6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function N6(e){let t=new Map;for(let n of hS(e.presets))for(let r of Wy(vS(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=By(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function P6(e){let t=[],n=new Set;for(let r of Wy(rS(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 F6(e,t,n){let r=new Set([...FR(e,t).keys()].flatMap(e=>ZR(e,n)));return Array.from(r).sort()}function I6(e){return e===null?null:e.config}const L6=[`vars`,`segments`,`config`];function R6(e){return typeof e==`string`&&L6.includes(e)}const z6=e=>({resp:e,exitAfterFlush:null,settled:d6}),B6=e=>({kind:`reply`,...e}),V6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},H6=(e,t)=>B6(z6({ok:!1,error:t,code:e,daemonV:3}));function U6(e){let t=tq(e.sessionId);if(!t.ok)return H6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return H6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Wb.join(`, `)}): it predates the lane toggles — update it`);let n=Zb(e.lane);return n===null?H6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Wb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function W6(e,t,n,r,i){if(t.kind===`url`)return B6(z6(await Q6(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?H6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?U6(a):typeof a.kind!=`string`||!Object.hasOwn(V6,a.kind)?H6(`BAD_REQUEST`,`unknown kind`):B6(await G6(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,settled:d6})}async function G6(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,effectSessions:m,menuIdle:h,journalTurns:g,sessionState:_,tmuxStatusLines:v,watcherRegistry:y,limits:b,handlerProbes:S,renderSightings:C,bundle:w,sourceDigest:T,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,settled:d6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return z6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return z6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:K6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,collector:e.collector.stats(),effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:_.size(),observers:_.observers(),revision:_.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:v.stats(),watchersActive:y.size(),dirWatchesActive:y.dirWatches(),nextRestartReason:b.describeNextRestart(),handlerProbes:S.list(),clients:C.list(Ve(new Date(o.now()))),bundle:w,sourceDigest:T,daemon:b.serving(),doctorStores:RZ(ee)})});if(t.kind===`render`){let c=new Date(o.now()),l=Ve(c),u=o.monotonic(),d=Fe(r.at,u),f=[];a.requestsTotal++;let p=r.id,m=T6(t,a,e.log,e.home),h=(t,n)=>C.see(t.hookData.session_id,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Xo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Nj(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.hookData.session_id,m.req,p));let g=t=>{t.outcome.kind!==`ok`&&a.requestsErrored++,R3(f,{req:String(r.id),timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:s,line:c}=V3(`render`,f,t.outcome,A(o,u));return e.log(s,c),{resp:t.resp,exitAfterFlush:null,settled:t.settled}};if(!m.ok)return g(i8(m.problems));let _=await h6(e.renderer,e.collector,o,m.req,p,l,u+mr(m.req.deadline,r.at,{epochMs:c.getTime(),monoMs:u}),f).catch(e=>({outcome:{kind:`threw`,error:e},resp:U3(e),seen:`failed`,settled:d6}));try{return h(m.req,_.seen),g(_)}catch(e){throw _.settled(!1),e}}if(t.kind===`click`)return z6(await X6(e,r,n,i,(n,r)=>Z6(e,t,n,r)));if(t.kind===`debug`){if(!R6(t.what))return z6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${L6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?Y6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Ox(`colorCompatibility`)):J6};return z6({ok:!0,debug:E6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function K6(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const q6={endcaps:Ox(`endcaps`),colorCompatibility:Ox(`colorCompatibility`),wrap:Ox(`autoWrap`),padding:Ox(`padding`),width:1/0},J6=new Map;function Y6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Ej(i,{...q6,colorCompatibility:t}));return n}async function X6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`req`,String(t.id)],[`queued`,`${Fe(t.at,o)}ms`]],c=await i(s,()=>n()||r());R3(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=V3(`click`,s,c,A(a,o));return e.log(l,u),n8(c)}async function Z6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};R3(n,{via:`cli`});let{verb:a,value:o}=t;return typeof a!=`string`||typeof o!=`string`?{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof a} and ${typeof o}`]}:$6(()=>t8(e,a,o,i,n,r))}async function Q6(e,t,n,r,i){return X6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(R3(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Xn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Xn].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o=ja(a);if(!o.ok)return{kind:`bad-request`,problems:[o.problem]};let s={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return $6(()=>t8(e,o.verb,o.value,s,n,r))})}async function $6(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof JG?{kind:`closing`,error:e}:e instanceof YG?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const e8={link:`verb`,"tmux-status":`linkVerb`};async function t8(e,t,n,r,i,a){if(t===`tmux-status-click`)return R3(i,{verb:t}),r8(e,n,i,a);R3(i,{[e8[r.via]]:t});let o=h1(t,n);o===null?R3(i,{sid:`-`}):o.ok&&R3(i,{sid:o.id});let s=o?.ok?e.collector.holding(o.id):()=>{};try{let s=await e.renderer.answer({kind:`event`,at:Ue(e.clock),event:{kind:`click`,verb:t,value:n,session:o,arrival:r,gone:a}});switch(s.kind){case`answered`:return i.push(...s.output.record),{kind:`ok`};case`threw`:throw i.push(...s.record),s.error}}finally{s()}}function n8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:return U3(e.error)}}async function r8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(R3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=ja(s.url);return t.ok?t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):t8(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await d$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,c$,e.tmp),{kind:`ok`}}const i8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},settled:d6});function a8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return E.join(e,`update-act`,n)}const o8={kind:`idle`};function s8(e){if(e===null)return o8;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const c8=e=>({stdout:E.join(e,`stdout`),stderr:E.join(e,`stderr`),status:E.join(e,`status`)}),l8=e=>E.join(e,`record.json`);function u8(e){let t;try{t=s.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function d8(e){let t=qo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function f8(e,t){let n=E.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(E.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const p8=e=>e.now()-o.uptime()*1e3;async function m8(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function h8(e){try{return JSON.parse(s.readFileSync(l8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const g8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function _8(e,t,n,r){let i=null;async function a(a){let o=E.join(e,String(a)),c=h8(o);if(c===null)return null;if((i===null||!g8(i.record,c))&&(i={record:c,ours:await m8(c,t,n,p8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=c8(o),u=kt(l.status),d=u===null?null:d8(l.stderr)??d8(l.stdout);if(!s.existsSync(o))return null;let f={act:a,record:c,alive:i.ours,end:u,lastLine:d};return f.alive||(i.final=f),f}return{async read(){let t=null;for(;;){let n=u8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${E.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function v8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(E.join(e,`.claim-`));try{return s.writeFileSync(l8(r),JSON.stringify(n)),s.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{s.rmSync(r,{recursive:!0,force:!0})}}async function y8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=E.join(t,String(c)),u=e.launchJobSync(i,c8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!v8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return b8;if(u8(t).some(e=>e>c))return f8(t,c),b8;d=!0}finally{d?u.release():u.withdraw()}for(let e of u8(t).filter(e=>e<c))f8(t,e);return{ok:!0,act:c}}const b8={ok:!1,reason:`another act claimed this bundle first`};function x8(e,t,n){let r=c8(E.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function S8(e,t,n){if(t.kind===`pending`)return Oo(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}var C8=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function w8(e){return e.kind===`source`?e.newer.digest:cs(e.newer)}const T8=e=>`${e.version} [${en(e.digest)}]`;function E8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:T8(e.newer),running:T8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:cs(e.newer),running:cs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${us}@${cs(e.newer)}`,`install`]}}}}const D8={offer:[],failure:[]};function O8(e,t,n){if(e===null)return D8;let r=w8(e);if(!n.enabled||n.dismissed===r)return D8;let i=E8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?MB(`[${i.busy}]`,null):MB(`[${i.act}]`,Ta([{verb:ca,args:[n.sessionId]}])),c=[MB(a,null),s,MB(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,VF,r]}])),MB(`[disable]`,Ta([{verb:Xi,args:[n.sessionId,HF,`false`]},{verb:Wi,args:[n.sessionId,UF,`false`]}]))];return{offer:[{severity:OB,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function k8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return A8(t)}}function A8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function j8(e){switch(e.kind){case`current`:return[`info`,`build: current ${T8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${T8(e.source)}, running ${T8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function M8(e){switch(e.kind){case`current`:return[`info`,`release: current ${cs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${cs(e.latest)}, running ${cs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${cs(e.installed)}, latest ${cs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function N8(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,gates:f,onApplied:p,log:m}=e,h=Oo(`unread`),g=Oo(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new JG(`apply-update`);return t},v=_8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new C8,w=e=>C.run(`acts`,e),T=!1,ee=[],te=(e,t)=>{ee.push(n.every(t,e,{unref:!0}))},E=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function ne(){let e=E(),t=e===null?null:w8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(VF,[t])})}function D(){let e=T?I:k8(h,g),r=S8(t.get(),e,Ue(n));(0,X.runInAction)(()=>t.set(r)),ne()}function re(){let e=sn(a,()=>rn(o));return h=F(e),x(j8(e)),D(),e}async function ie(){let e=fs(tn,await ds(us,d,u,n));g=F(e),S(M8(e)),D()}let O=null,ae=Ne(m);async function oe(e){try{let t=await e();return O=null,{ok:!0,value:t}}catch(e){return e instanceof JG?{ok:!1,error:e.message}:(O=`update act files (${s}): ${e.message}`,ae([`error`,O]),{ok:!1,error:O})}}function se(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=x8(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;m(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function ce(){let e=await oe(async()=>{let e=await v.read();return T||se(e),e});if(T||!e.ok)return;let t=s8(e.value);y===null&&t.kind===`running`&&m(`info`,`apply-update: act ${t.act} is running; watching it`),y?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(m(`info`,`apply-update: act ${t.act} succeeded`),re(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await w(ce),!T&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=re();te(re,c),ee.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),te(()=>void ie(),l))},close(){T=!0,D(),ee.forEach(e=>e())},notice:e=>O8(E(),y??o8,e),running:()=>w(async()=>{let e=await oe(()=>v.read());return e.ok&&s8(e.value).kind===`running`}),error:()=>O,act:()=>w(async()=>{if(T)throw new JG(`apply-update`);let e=await oe(()=>v.read());if(T)throw new JG(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=E();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=E8(t),a=e.value;if(s8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await y8(r,s,a===null?null:a.act,w8(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new Z(`apply-update: ${o.reason}`);m(`info`,`apply-update: act ${o.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),y={kind:`running`,act:o.act}})}}function P8(){return X.observable.box(Oo(`unread`),{deep:!1})}function F8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function I8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function L8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:F8(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=F8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!I8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var R8=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}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 z8=`pass`,B8={okMs:5*6e4,failedMs:45e3},V8=B8.okMs;function H8({failures:e}){return PY(B8,e,V8)}function U8(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function W8(e){return`git:${e}`}function G8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:E.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Ac(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${jc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function K8(e){return e.kind===`ok`?e.value.branch:void 0}function q8(e){e.missed=!0,NJ(e,`unread`)}function J8(e,t){return e.missed&&e.reading.get().kind===`pending`&&MJ(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function Y8({value:e,pr:t}){let n=FJ(e);return n.kind===`ok`?F({...n.value,pullRequest:FJ(t)}):n}const X8=L(`git cache closed`,`read`);function Z8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Q8=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.forgeLookups=new Ao(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new dY(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new gV({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return LJ(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>Y8(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:X8};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}built(e){let t={period:new FY(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:I,reading:AJ(),inFlight:null},n={root:e,refresh:new R8,watch:this.followWatch(e,null).watch,period:new FY(()=>{n.refresh.share(z8,()=>this.refreshPass(n))},this.clock),value:{reading:AJ(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=G8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(z8,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e){return e.holders++,e.value.missed&&(q8(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(z8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(W8(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch(Z8(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,MJ(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of eJ(i.value))o.add(e);let s=K8(i),c=s===void 0?J8(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,U8(n),o.size===0?F(null):L([...o].join(`; `),`read`),A(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(Z8(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(q8(r),`owed`):(NJ(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,MJ(r,a.outcome),r.period.landed(H8(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch(Z8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,A(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(MJ(t,i),t.period.landed(H8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);PJ(e.value,t),PJ(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},$8=class{static usageDir(e){return E.join(e,`usage`)}static locksDir(e){return E.join(e,`locks`)}static isLocked(e,t){let n=E.join(this.locksDir(e),t);if(!s.existsSync(n))return!1;try{let e=s.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),s.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),s.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=E.join(this.locksDir(e),n),a=t.monotonic(),o=String(process.pid);for(;t.monotonic()-a<r;)try{return await s.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await Le(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=E.join(this.locksDir(e),t);try{await s.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([s.promises.mkdir(e,{recursive:!0}),s.promises.mkdir(this.usageDir(e),{recursive:!0}),s.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=E.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await Le(t,75);continue}try{let e=await s.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await Le(t,75)}}return k(`Failed to read ${n} 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,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=E.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},c=JSON.stringify(o);await s.promises.writeFile(a,c,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const e5={"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 t5=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(e,t){let n=t.now()-1440*60*1e3;return await $8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await $8.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){k(`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)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(e5).length} models`),this.executionCache=e5,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e5).length} models`),e5)}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,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}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,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}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`}},n5=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 r5(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 i5={okMs:60*1e3,failedMs:10*1e3},a5={calculatedCost:null,tokens:null,tokenBreakdown:null};function o5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function s5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const c5={entries:0,cost:0,breakdown:s5(),days:new Map};async function l5(e,t,n,r){let i=BJ(new Date(o5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await t5.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=BJ(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...RJ};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function u5(e){let t=0,n=0,r=s5(),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)??{...RJ};zJ(n,t),i.set(e,n)}}if(t===0)return{usage:a5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{usage:{calculatedCost:n,tokens:a,tokenBreakdown:r},days:i}}function d5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function f5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!d5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...RJ};zJ(r,t),n.set(e,r)}return Object.fromEntries(n)}async function p5(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))}function m5(e,t){(0,X.runInAction)(()=>e.set(t))}var h5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new n5;scans;daySets=new Map;speedFlight=new n5;requestFlight=new n5;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new dY(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new LY({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??i5,watch:IY,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async()=>{let e=await r().record;return e.kind===`failed`?e:F(e.kind===`ok`?e.value.usage:a5)},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e){let t=this.sessions.get(e);if(t===void 0)return Oo(`unread`);let n=t.failure.get();return n===null?F(t.record?.usage??a5):L(n,`read`)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.monotonic(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,A(this.clock,i)),m5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}declareToday(e,t){if(this.closed)return LJ(L(`usage store closed`,`read`));let n=JJ(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||d5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}async observed(e,t,n){let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return m5(this.hold(e).speed,t),t;let r=r5(t.kind===`ok`?t.value.usage.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return m5(this.hold(e).speed,s),s})}speedOf(e){return this.sessions.get(e)?.speed.get()??Oo(`unread`)}async ingest(e,t,n,r){let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,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)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,usage:s.value.usage,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>ie(e,`projects`)+O),i={roots:r,sums:new k1(`today over ${e.join(`,`)}`,()=>f5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await ZJ(e,D(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of oY(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 sY(e,r,c5,(e,t)=>l5(e,t,un(this.host),this.clock));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 oY(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...u5(i),mainStamp:a})}async scan(e){try{let t=o5(this.clock.now()),n=await YJ(e),r=[];for(let e of n){let n=await XJ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await XJ(Lo(n));if(a===void 0||a.mtimeMs<t)continue;let o=tq(i.slice(0,-6));if(!o.ok){this.log(`warn`,`usageStore scan: transcript ${JSON.stringify(i)} names no session: session id ${o.problem}`);continue}r.push({sessionId:o.id,path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await p5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=BJ(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}};const g5={command:null,todos:[],pending:[],done:[]};function _5(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 v5(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 y5(e,t){if(t.isSidechain)return e;let n=v5(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=_5(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 b5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>_5(e,t.name),[]),done:e.done}}var x5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new lY(g5,y5,(e.ledger??new dY(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return S5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:S5(e,t)}};function S5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(b5(t.value))}const C5=3e4;var w5=class{names;constructor(e){let t=e.logger??Pe;this.names=new LY({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>T5(e.launcher,t),every:()=>({okMs:C5,failedMs:C5}),watch:IY,maxEntries:64,logger:t,ledger:e.ledger??new dY(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function T5(e,t){let n=await pc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const E5=6e4,D5={okMs:E5,failedMs:E5};function O5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function k5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var A5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>D5,watch:IY,maxEntries:1,logger:t,ledger:e.ledger??new dY(t),clock:e.clock};this.name=new LY({...n,name:`host.name`,read:()=>k5(`name`,()=>O5(o.hostname()))}),this.user=new LY({...n,name:`host.user`,read:()=>k5(`user`,()=>o.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},j5=class{known=new cY(64);refreshes;constructor(e,t=Pe,n=new dY(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=M5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.monotonic(),i=PN(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function M5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const N5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function P5(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}var F5=class{known=new cY(256);refreshes;constructor(e,t=Pe,n=new dY(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n){let r=this.clock.monotonic(),i=await I5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,A(this.clock,r)),i}};async function I5(e){let t=await L5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function L5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=R5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function R5(e,t){let n=e.toString(`utf8`).split(`
|
|
484
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!N5.test(t))continue;let r=P5(t);if(r!=null)return r}return null}const z5=e=>sz(e),B5=e=>E.join(e.storage.folder,z5(e.sessionId)),V5=e=>JSON.stringify([e.folder,e.generation]),H5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var U5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Dc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new LY({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(B5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:IY,maxEntries:256,logger:e.logger,ledger:e.ledger??new dY(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{s.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!Oc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(V5(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${V5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(V5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=V5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>H5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(E.join(n.folder,E.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(B5(e)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&Oc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>H5(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>H5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(V5(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=zc(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=B5(e),r;try{r=await s.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=WY(r);return i.kind===`failed`?L(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${A(this.clock,t)}ms`;try{let t=await s.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=E.join(e.folder,a.name);try{let{mtimeMs:r}=await s.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&z5(t.sessionId)===a.name);if(r>=n||o)continue;await s.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function W5(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new A5({clock:n,logger:r,ledger:i}),gitProvider:new Q8({inner:new OJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new h5({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new hY({clock:n,logger:r,ledger:i}),metricsProvider:new TY({clock:n,logger:r,ledger:i}),activityProvider:new x5({clock:n,logger:r,ledger:i}),tmuxService:new w5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new j5(n,r,i),cacheExpiry:new F5(n,r,i),managedStorage:new U5({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),sourceRuns:e.sourceRuns,faults:new jY,log:e.logger,clock:n}}function*G5(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*dne(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);yield*Object.values(t.partials??{})}for(let t of hS(e.presets)){for(let n of Wy(vS(e,t).node))n.when!==void 0&&(yield n.when);let n=xS(e,t);for(let e of sy){let t=n[e];cy(t)&&(yield t)}}for(let[,t]of G5(e))for(let[,e]of $y(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of JF(t))yield e}function fne(e,t,n){let r=kU(t),i=new Set,a=new Set,o=new Set;for(let e of dne(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of zR(e,t.helpers))a.add(n);for(let n of GR(e,t.helpers))o.add(n)}for(let[,e]of G5(t))for(let{reaches:t}of r.ofVariable(e))for(let e of t)i.add(e);let s=new Set(a);for(let e of a){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)s.add(e)}let c=new Set,l=new Set(n);for(let e of s){let n=t.actions[e];if(n!==void 0&&(`set`in n&&c.add(n.set),`insertSegment`in n&&l.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)l.add(e)}for(let e of hS(t.presets))for(let n of Wy(vS(t,e).node))n.kind===`segment`&&l.add(n.name);let u=(e,t)=>i.has(e)||t.kind===`state`&&c.has(t.key),d=e=>[...e].filter(e=>!Ii(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(G5(e));return[...f(`variable`,p.keys(),e=>u(e,p.get(e))),...f(`action`,Object.keys(e.actions??{}),e=>s.has(e)),...f(`helper`,Object.keys(e.helpers??{}),e=>o.has(e)),...f(`segment`,Object.keys(e.segments??{}),e=>l.has(e))]}function pne(e){return Math.floor(Math.max(e/4,e*Br-67108864))}const mne={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function K5(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=e.name===void 0?void 0:n.variables[oz(vk(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[vk(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>yk(e)(t)&&t!==oz(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${yA(e,`<default>`)}: projections=${[...NU(n).keys()].join(`,`)||`-`} instantSegments=${y3(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e.path} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}const hne=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},q5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${hne(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function gne(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(q5(t))} state=${n} files=${R(yA(e.configLayers,`<bundled default>`))} awaiting=${r(e.repos.awaiting)} declined=${r(e.repos.declined)} unproven=${e.repos.unproven.length===0?`-`:JSON.stringify(e.repos.unproven)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function _ne(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function J5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function vne(e,t){return new Set(hS(e.presets).filter(n=>vS(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function yne(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,E.join(e.projectDir,Bz)])];return lV({named:[...fB(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:a})}function bne(e){return e.filter(Boolean).join(`
|
|
485
|
-
`)||null}const Y5=e=>e instanceof Error?e.message:String(e);function X5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function xne(e){let{loaded:t,chain:n}=e;return G1({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:X5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...X5(t.installed),checkout:t.installed.checkout,roots:t.installed.roots,unreached:t.installed.unreached},config:t.config,dropped:t.dropped.map(e=>e.message),placed:null},sources:[...e.sources].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.folder,t.generation])})}function Sne(e,t){let n=new Map,r=new Map;for(let[i,a]of Object.entries(e.variables)){if(a.kind!==`source`)continue;let e=n.get(a.storage)??t.keyFor(a.storage);n.set(a.storage,e),r.set(i,e)}return r}function Z5(e,t,n){let r=[];try{let i=OW(t.locs,t.layers,eG,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Sne(i.config,n)};return{kind:`resolved`,...a,key:xne(a),warnings:r}}catch(e){return e instanceof pb&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function Q5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??eG,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new z1(t.clock),m=new i0(p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=p3(o,m,n,t.compile??f3(t.signer),wne),f.push(...h.loadWarnings);let r=m.view();f.push(...g3(o,r,n,n7)),r.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof pb&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:vne(l,u),fileHeldSettings:jG(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>fne(e.raw,i.placed,d)).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},sources:e.sources}}}function $5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:A(i,e.started)},o=t=>bne([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:Y5(r.cause),cause:r.cause}}}function Cne(e,t,n,r,i=null){let a=Z5(t,n,r.storage);if(a.kind===`failed`)return $5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:Q5(a,r);return $5(e,n,a.warnings,o,r.clock)}function e7(e,t,n,r,i=null){let a=r.clock.monotonic(),o=gB(r.locations,nV(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return Cne({repos:s,advisories:[CB(r.locations,e,t),xB(o),lB(s)],started:a},t,c,r,i)}function t7(e,t,n){let r=Z5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:Q5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${Y5(i.cause)}`,{cause:i.cause});return i.state}const wne=new Set([`directory`]),n7=new Set([`view`]);function Tne(e,t,n,{source:r,changed:i,log:a}){let o=n.hookData.session_id,s=e.registry.view();g3(e.config,s,t,n7);let c=X.observable.box(n,{deep:!1}),l;try{l=r({sessionId:o,state:e,store:s.variableStore,requested:()=>c.get()})}catch(e){throw s.dispose(),e}B4(e.compiled,s.variableStore,s,l);let u=(0,X.reaction)(()=>[l.payload(),l.selections(),s.published(),e.registry.published()],()=>i(o),{equals:X.compareShallow,fireImmediately:!0,onError:e=>a(`error`,`session view change threw sid=${JSON.stringify(o)}: ${String(e)}`)});return{sessionId:o,state:e,store:s.variableStore,registry:s,source:l,requested:e=>{e!==c.get()&&(0,X.runInAction)(()=>c.set(e))},facts:()=>c.get(),lastRenderCellsBySegment:new Map,retire:u,dispose:()=>(u(),s.dispose())}}const Ene=({state:e,registry:t})=>[...[...e.sources].map(([e,t])=>({kind:`plugin`,source:e,storage:t})),...t.subscriptions().map(e=>({kind:`run`,run:e}))];var Dne=class{entries=new Map;answersWatch;closed=!1;due=new Map;walk=null;holds=new Map;views=new Map;copies=new Map;viewHolds=new Map;pins=new Map;openFailures=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??Pe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},s.mkdirSync(eV(e.stateDir),{recursive:!0});let{dir:n,name:r}=oV(tV(e.stateDir));this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??v3(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=J5(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n,null);a.state!==null&&this.log(`info`,K5(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??t7(t,a.repos.plugins,this.deps),watch: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=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++;let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=jo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(J5(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let i=n.hookData.session_id,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o;try{o=this.opened(e,t,n,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),o}opened(e,t,n,r){let i=n.hookData.session_id,a;try{a=Tne(t,e.cwd,n,{source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(i,{error:e,facts:n}),e}return this.openFailures.delete(i),this.views.set(i,a),this.viewHolds.set(a,{entry:e,holders:0,retired:null}),this.log(`info`,`session view opened sid=${JSON.stringify(i)} by=${r} cwd=${e.cwd} views=${this.views.size}`),a}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),this.views.has(e.sessionId)||this.copies.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}retireSession(e){this.openFailures.delete(e);let t=this.views.get(e);t!==void 0&&this.retireView(t,`idle`)}subscriptions(){return{sources:new Map([...this.views].map(([e,t])=>[e,Ene(t)]))}}close(){if(this.closed)return;this.closed=!0,this.walk?.(),this.walk=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n,r){if(this.closed)throw Error(`render cache used after close`);return e7(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.due.delete(t),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,due:this.due.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`)}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,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,_ne(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){this.due.delete(e);let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,K5(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state),this.retire(r,`reload`,{entry:e,state:i.state})),this.fit(e),this.refreshWatcher(e,i),this.observers.onReload?.(e,n,t,i.kind)}reloadEvery(e){for(let t of this.entries.values())this.due.set(t,e);this.armWalk()}armWalk(){this.walk!==null||this.due.size===0||(this.walk=this.deps.clock.defer(()=>this.walkOne()))}walkOne(){this.walk=null;let e=null;for(let t of this.entries.values()){let n=this.due.get(t);n!==void 0&&(e=[t,n])}if(e===null)return;let[t,n]=e;try{this.reloadInto(t,n)}catch(e){this.log(`error`,`every-entry reload threw projectDir=${R(t.projectDir)} cwd=${R(t.cwd)} configFile=${R(t.configFile??`-`)} cause=${R(q5(n))}: ${x(e)}`)}finally{this.armWalk()}}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=yne(e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const One=e=>!oq(e)&&!SN(e)&&e!==`update.dismissed`&&e!==Bi;var kne=class{past=X.observable.map(void 0,{deep:!1});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:QK(e,One,(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 Z(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.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){(0,X.runInAction)(()=>{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)})}},r7=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};const i7=(e,t)=>e.kind===`ok`?F(t(e.value)):e;function Ane(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest}}const a7=(e,t)=>{let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>Object.is(n,Reflect.get(t,e)))};function jne({pullRequest:e,...t}){return t}function o7(e,t,n,r,i){let{lanes:a}=n,o=(e,t)=>S8(e,t,i),s=e?.builtins,c={session:o(s?.session,a.usage),today:o(s?.today,n.today),speed:o(s?.speed,a.speed),context:o(s?.context,a.context),metrics:o(s?.metrics,a.metrics),activity:o(s?.activity,a.activity),cache:o(s?.cache,a.cache),autocompact:o(s?.autocompact,a.autoCompact),git:o(s?.git,i7(a.git,jne)),pr:o(s?.pr,Ane(a.git)),tmux:o(s?.tmux,i7(a.tmuxSession,e=>({session:e}))),hostName:o(s?.hostName,a.hostName),hostUser:o(s?.hostUser,a.hostUser)},l=Object.fromEntries([...a.sources].map(([t,n])=>[t,o(e?.sources[t],n)])),u=Object.fromEntries([...a.runs].map(([t,{reading:n,fault:r}])=>{let i=e?.runs[t],a=o(i?.reading,n);return[t,i!==void 0&&i.reading===a&&i.fault===r?i:{reading:a,fault:r}]})),d={builtins:c,sources:l,runs:u,update:r,diagnostics:n.faults};return e!==void 0&&a7(c,e.builtins)&&a7(l,e.sources)&&a7(u,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:2,session:t,seq:e===void 0?1:e.seq+1,...d}}function s7(e,t){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason===t?e:{...e,seq:e.seq+1,diagnostics:[...e.diagnostics.filter(e=>e.kind!==`stamp`),{kind:`stamp`,reason:t}]}}function c7(e){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason??null}const Mne=e=>({hookData:e.hookData,cwd:e.cwd,hints:e.hints}),Nne=e=>({plugins:new Map(e.flatMap(e=>e.kind===`plugin`?[[e.source,e.storage]]:[])),runs:new Map(e.flatMap(e=>e.kind===`run`?[[e.run.digest,e.run]]:[]))}),Pne=(e,t)=>e.plugins.size===t.plugins.size&&[...e.plugins].every(([e,n])=>{let r=t.plugins.get(e);return r!==void 0&&H5(n,r)})&&e.runs.size===t.runs.size&&[...e.runs.keys()].every(e=>t.runs.has(e));function l7({stop:e,holds:t}){e(),t.close()}var Fne=class{records=new Map;stopSweep=null;constructor(e){this.deps=e}requested(e){let t=Mne(e),n=e.hookData.session_id,r=(0,X.runInAction)(()=>{let e=this.records.get(n);if(e===void 0){let e=this.open(n,t);return this.records.set(n,e),e.stamped.document}e.active=!0;let{phase:r}=e;r.kind===`live`&&r.declared.set(this.declared({...e,locator:t},r.holds));let i=r.kind===`live`?r:this.live(e,t);return e.phase=i,this.stamp(e,i.inputs.get()),e.stamped.document});return this.armSweep(),r}subscribed({sources:e}){for(let t of e.keys())this.records.has(t)||this.deps.log(`error`,`subscriptions name session ${JSON.stringify(t)}, which the collector has no record of`);(0,X.runInAction)(()=>{for(let t of this.records.values()){let n=Nne(e.get(t.session)??[]);if(Pne(n,t.subscriptions))continue;t.subscriptions=n;let{phase:r}=t;r.kind===`live`&&r.declared.set(this.declared({...t,locator:r.declared.get().locator},r.holds))}})}holding(e){let t=this.records.get(e);return t?.phase.kind===`live`?(t.clicks++,()=>{t.clicks--,t.active=!0}):()=>{}}sweep(){for(let e of this.records.values())e.phase.kind===`live`&&(e.active?e.active=!1:e.clicks===0&&!this.deps.watched(e.session)&&this.retire(e,e.phase))}stats(){let e=[...this.records.values()];return{sessions:e.length,retiring:e.filter(e=>e.phase.kind===`retiring`).length}}close(){this.disarmSweep();for(let{phase:e}of this.records.values())e.kind===`live`&&l7(e);this.records.clear()}open(e,t){let n={plugins:new Map,runs:new Map},r=this.reader({session:e,locator:t,subscriptions:n}),i=r.inputs.get(),a;try{if(i.kind===`failed`)throw Error(i.reason);a=o7(void 0,e,i.readings,i.update,Ue(this.deps.clock))}catch(e){throw r.holds.close(),e}let o={document:a,from:i};return{session:e,stamped:o,subscriptions:n,active:!0,clicks:0,phase:this.watch(e,o,r)}}live(e,t){return this.watch(e.session,e.stamped,this.reader({...e,locator:t}))}reader(e){let t=new r7,n=X.observable.box(this.declared(e,t),{deep:!1});return{holds:t,declared:n,inputs:(0,X.computed)(()=>this.read(n.get()))}}watch(e,t,n){let r=(0,X.reaction)(()=>n.inputs.get(),n=>(0,X.runInAction)(()=>{n!==t.from&&this.stamp({session:e,stamped:t},n)&&this.deps.deliver({kind:`world-state`,worldState:t.document})}),{onError:t=>this.deps.log(`error`,`world state stamp threw sid=${JSON.stringify(e)}: ${x(t)}`)});return{kind:`live`,...n,stop:r}}declared({session:e,locator:t,subscriptions:n},r){let i=JSON.stringify(e);try{let{result:{lanes:e,faults:a},acquired:o,released:s}=r.declare(()=>gX(this.deps.owners,r,t,n));for(let e of a)this.deps.log(`error`,`session declaration threw sid=${i} ${e}`);return o+s>0&&this.deps.log(`info`,`session declared sid=${i} acquired=${o} released=${s} held=${r.size}`),{locator:t,lanes:e}}catch(e){return this.deps.log(`error`,`session declaration threw sid=${i}: ${x(e)}`),{locator:t,lanes:mX(L(`session declaration threw: ${String(e)}`,`read`),n)}}}inputsOf(e){return{...e,deps:this.deps.owners}}read({locator:e,lanes:t}){try{return{kind:`read`,readings:_X(this.inputsOf(e),t),update:this.deps.update()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}}stamp({session:e,stamped:t},n){let r=t.document,i=n.kind===`failed`?s7(r,n.reason):this.assembled(r,n,Ue(this.deps.clock)),a=i===r?null:c7(i);return a!==null&&this.deps.log(`error`,`world state sid=${JSON.stringify(e)}: ${a}`),t.document=i,t.from=n,i!==r}assembled(e,t,n){try{return o7(e,e.session,t.readings,t.update,n)}catch(t){return s7(e,`stamping the world state: ${String(t)}`)}}retire(e,t){l7(t);let n={kind:`retiring`};e.phase=n,this.deps.log(`info`,`session retired sid=${JSON.stringify(e.session)}`),this.deps.deliver({kind:`retire`,session:e.session}).then(()=>{e.phase===n&&this.records.get(e.session)===e&&this.records.delete(e.session),this.records.size===0&&this.disarmSweep()})}armSweep(){this.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.sweep(),{unref:!0}))}disarmSweep(){this.stopSweep?.(),this.stopSweep=null}},Ine=class{documents=X.observable.map(void 0,{deep:!1});take(e){let t=this.documents.get(e.session);if(t!==void 0&&e.seq<=t.seq){if(e.seq===t.seq&&(0,X.compareStructural)(e,t))return;throw Error(`world state seq ${e.seq} for session ${JSON.stringify(e.session)} does not follow the held seq ${t.seq}`)}(0,X.runInAction)(()=>this.documents.set(e.session,e))}of(e){let t=this.documents.get(e);if(t===void 0)throw Error(`no world state for session ${JSON.stringify(e)}: the host hands one in with the config ahead of every request`);return t}drop(e){(0,X.runInAction)(()=>this.documents.delete(e))}};function Lne(e){return({sessionId:t,state:n,store:r,requested:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>lG(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n}=i();return{hookData:t,hints:n,home:e.home}}),c=r.derive(`session.draw`,`computed`,()=>({sources:[...n.sources.keys()],effective:o.read(),configFacts:{...MG(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),l=()=>e.worldStates.of(t),u=r.derive(`session.payload`,`computed`,()=>wX(l(),s.read(),c.read()));return{session:t,payload:()=>u.read(),effective:()=>c.read().effective,facts:l,run:e=>l().runs[e]??MY,hints:()=>s.read().hints,failure:()=>c7(l()),selections:()=>c.read().effective}}}const u7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,d7=`#{session_id} #{client_control_mode} #{pane_id}`;function f7(e){let t=new Set;for(let n of e.split(`
|
|
486
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
487
|
-
`)){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
|
|
483
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function t4(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}`}})}const n4=e=>e.kind===`failed`?a0:e;function r4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function i4(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:n,opened:r.length>0,ground:i},deeper:r}}function a4(e){return{...e,cells:e.cells.map(d0)}}function o4(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,...s4(e,r)]}function s4(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 c4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:o4(e.direction,e.children.map((t,i)=>n(t,[...r,l4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function l4(e,t){return e.steps[t]}function u4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=d4(e);return{width:f4(t),reach:p4(t)}}function d4(e){let t=e.children.map(u4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const f4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),p4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function m4(e,t){let n=d4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=Ry[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),p4(n),f4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const h4={compile(e,t){let n=m4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Wy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),o4(e.direction,e.children.map((n,r)=>t.renderChild(n,n4(t.gate),l4(e,r))))}},g4={drop:e=>e.place,above:()=>`above`},_4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},v4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:zy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Gy(t.path),void 0),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,y4(e,t))};function y4(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=V1(t.scope,e.settings);if(t.gate.kind===`failed`)return T4(e,r,t,t.gate.message);try{let i=t.placement(e),a=r4(t.gate,i.gate());if(a.kind===`failed`)return T4(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return T4(e,r,t,s.message);let c=Hx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:$k(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?b4(f.variable):x4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?S4(p.segment,u):C4(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:a0,h.disclosure).map(e=>({...e,place:g4[v.placement](e)})),b=(e,t,n)=>m0(x0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?_4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new K(` `.repeat(w4(u0(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],ee=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(u0)),[...te,...ee]}catch(n){return T4(e,r,t,n.message??String(n))}}const b4=e=>({kind:`waiting`,variable:e});function x4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=lI(e);if(t===void 0)throw e;return b4(t.variable)}}function S4(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:e4(x0(r,c)).map((e,t)=>({cells:m0(e,{...l,lead:t===0?x0(i,c):[],trail:t===0?x0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:m0(x0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function C4(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=x0(E4(e.lead,e,t,n),l),d=x0(E4(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return m0(x0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function w4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function T4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:m0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:$k(n.palette)},lead:E4(e.lead,e,t,n),trail:E4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function E4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=lI(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const D4={container:h4,segment:v4};function O4(e){return D4[e]}var k4=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?A4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const A4={kind:`hidden`},j4={palette:`theme`,style:`style`,effect:`effect`},M4=Ix.get(`colorCompatibility`),N4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function P4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function F4(e){if(e.ok)return e.value;throw e.error}const I4=e=>({read:()=>e}),L4=k_({basePalette:O_,palette:O_,decor:Uv});var R4=class{evaluated=0;memory=new k4;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&L4(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=z1(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(M4);return e.kind===`found`&&typeof e.value==`string`&&Dy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(N4,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return c4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=vF(e);return i===void 0?[]:[{name:i,address:n,palette:Hx(r.theme,t)}]}))}),t.bindInputs({session:()=>this.view.get().session,read:e=>this.inputAt(e),run:e=>this.view.get().run(e),drawnAt:()=>Oy(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=jk(e);return t===void 0?kk(e)===void 0?$1(this.view.get().payload(),e):$1(this.projected,e):Q1(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[j4[e]];if(t.kind===`decided`)return V4(t.name,null,null);let r=U4(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=W4(this.source,e,i.name,r.where,e=>{t=e}),V4(n,t,null)}case`pending`:return V4(n??my[e],null,i.variable);case`failed`:return n=my[e],V4(n,hy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!H4(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??my[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return s0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>c2(this.source.activeSegment,()=>s0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new G4(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:D0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=lI(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:P4(e)}),F4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:vF(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function z4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new R4(t,n,e,r);return e.views.set(t,a),a}function B4(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const V4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),H4=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function U4(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 view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function W4(e,t,n,r,i){switch(t){case`palette`:return qx(n,r,i).name;case`style`:return dy(n,e.styles).name;case`effect`:return xy(n).name}}var G4=class{where=K4(k_({palette:O_,region:Vv}));ground=K4(k_({colours:J4,bodyOpen:O_}));opened=K4(k_({colours:J4,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=V1(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?I4(o0):e.derive(`${t.id} when`,e.readsInstant(a),()=>c2(r,()=>s0(a,i))),this.open=d===void 0?I4(a0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>c2(r,()=>s0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return Z4(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return Q4(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?I4(e3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return $4(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),n3(n,r,this.affixes.read())}};function K4(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const q4=(e,t)=>e.hex===t.hex,J4=k_({palette:O_,drawnAt:O_,tint:q4,text:q4,bg:q4,disclosure:Wv});function Y4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const X4=e=>Rv(e.palette,e.disclosure,e.drawnAt);function Z4(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Xv(n,r,i)};return s2(e,Y4(t,c),e=>{let t=tA(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function Q4(e,t,n,r,i,a){return s2(e,Y4(t,n),e=>(e.bg=i?X4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function $4(e,t,n,r,i,a,o){return s2(e,Y4(t,n),e=>(e.bg=r?X4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const e3={lead:[],trail:[],drops:[]};function t3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return W0(t,X4(e).state,n)},get band(){return W0(t,X4(e).plane,n)},get close(){return q0(t,X4(e).state,n)},disclosure:r}}function n3(e,t,n){return{styles:t3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function r3(e,t,n,r,i,a,o){let s=Z4(e,t,n,r,i,void 0,void 0,o);return n3(s,Q4(e,t,s,a,!1,o),e3)}function i3(e,t,n,r,i){return t3(Z4(e,t,n,r,i,void 0,void 0,{}))}function a3(e,t,n,r){return{session:n,payload:()=>e,run:r,selections:()=>t}}function o3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Y1(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 s3(e,t){switch(Jy(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 c3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:o3(n.cache),parse:s3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:o3(n.cache),parse:s3(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function l3(e,t,n,r=mw.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function u3(e,t,n){let{compiled:r,loadWarnings:i}=f3(e,t,n.cwd,d3(n.signer),g3);return{...r,loadWarnings:i}}const d3=e=>(t,n)=>_3(n,e);function f3(e,t,n,r,i=g3){let a=p3(e),o=m3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:h3(e,t,n,i)}}function p3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Lx)n in t&&r.set(e,n);for(let[t,n]of tb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...MU(e)].sort(([e],[t])=>e<t?-1:1)}}function m3(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function h3(e,t,n,r){let i=$2(e),a=MU(e),o=[];for(let[s,c]of YR(e))if(r.has(i.get(s)))try{c3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const g3=new Set([`directory`,`view`]);function _3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>w0(i,`drawnAt`).registry.drawnAt(),o=a2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=mS(e.presets),u=fF(e),d=[e=>O2(i,o,e.now)],f=wU({extraFuncs:{...H0(i),...D2(i),...b2(i,o),...C2(i),...N2(i,o),...z2(i,o),...U2(s),...K2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=l3(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=O0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:l3(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=ab(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Dee(t,e,a,t=>String(w0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return O4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=_S(e,t);C.set(t,S(n,r,void 0))}let w=new Map(oy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of PU(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:b3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),ee={reads:TU({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:SU(d)},te=LU(ee),E=[...C.values()].flatMap(y3(y)).some(e=>te(m.get(e))),ne=E?new Set([...ee.clock,R2]):ee.clock,D=LU({...ee,clock:ne}),re=new Set([...m].flatMap(([e,t])=>D(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=LU({reads:TU({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:ee.projections,clock:ne});for(let e of Sz){let n=y[t][e];n!==void 0&&r(m.get(n))&&re.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,instant:re,layoutReadsInstant:E,styles:e.styles,runtime:i,views:new WeakMap}}function v3(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const y3=e=>t=>{let n=[];return c4(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function b3(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const x3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function S3(e,t,n,r,i){let a=C3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function C3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??my[e];case`failed`:return r({kind:`rule`,slot:e,message:hy(t.where,e,`the rule failed — ${n.error}`)}),my[e]}}function w3(e){return T3(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function T3(e){return e.kind===`container`?e.children.flatMap(T3):[e,...e.opens===void 0?[]:T3(e.opens.body)]}function E3(e,t,n,r,i,a,o,s){let c={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return z4(e,t,n,a3(c,a,o,s)),c}function D3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new NA(``),h=m.clockAt(a,_y[c.animationSpeed]),g=l.u(fU(a,h.timeline)),_=B4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:vj(v),padding:v.padding,seamCols:yj(v),preset:c.preset},i);let y=_.evaluated;l.u(D0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,i4),T=_.memory.from(C),ee=new Set,te={held:e=>T?.rules.get(e),waited:e=>ee.add(e),settled:w.rule},E=new Map,ne=e=>{let n=_.slot(e);if(E.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&ee.add(n.waited),n.name;let r=W4(t,e,S3(e,n.rule,_,p,te),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:D,style:re,effect:ie}=_.selections(),O=D.kind===`decided`?D:qx(ne(`palette`),``,x3),ae=re.kind===`decided`?re:dy(ne(`style`),e.styles),oe=ie.kind===`decided`?ie:xy(ne(`effect`)),se=O.value,ce=Wx(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:T,returned:i4,hold:a4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,n,i)=>{let a=n.kind===`hidden`?n:r4(n,_.gate(e)),o=a.kind===`failed`?{...a,report:()=>{let t=`when over ${w3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:a.message,message:`${t}: ${a.message} — what it gates is hidden`})}}:a,s={scope:_.scope,palette:ce,gate:o,padding:v.padding,region:i,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,a,o)=>r3(t.activeSegment,e,a,i,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Jv(i,n)),renderBody:(e,t,n)=>pe(e,t,Yv(n)),closeDisclosure:e=>U0(r.session(),e),placed:(e,t)=>w.placed(e,de.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>ee.add(e),decorations:(e,n)=>i3(t.activeSegment,e,n,i,r.drawnAt())};return O4(e.kind).render(e,s)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${fS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=t4(pe(me,o0,qv(S))).map(({line:e,row:t})=>{let n=y0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...Tj(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),w.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||T3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...ee].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:E}}catch(e){l.e=e}finally{l.d()}}const O3={moving:1e3/30,still:1e3},k3=[`data`,`state`,`reload`,`visibility`];function A3(e){return Ub.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 j3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const M3=(e,t)=>Hb[t].handsOff?e.resp:e.statusline,N3=e=>Math.round(1e3/e);var P3=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++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}feedOpen(e){return this.feeds.has(e)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}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}latest(e){return this.requests.get(e)?.req??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,t){let n=this.feeds.get(e);if(n===void 0)return Gee;let r=t-1,i=this.shown(n);return Yb(e=>{let a=n.rates.get(e);if(a===void 0)return qb;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}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.clock.monotonic(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&e.phase.clear(),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.clock.monotonic(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${x(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,N3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}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,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||M3(a,t)!==M3(i,t))&&j3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=M3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}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:eC(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=lY.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);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(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} ceiling=${N3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${k3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function F3(e,t){return Ub.filter(n=>e[n]&&Hb[n].handsOff&&t.has(n))}function I3(e,t){return{severity:kB,lines:[[jB(`[⟲ claude]`,Ta([{verb:na,args:[e,...t.map(e=>Hb[e].switch.setting)]}]))]]}}function L3(e,t){for(let n of Object.entries(t))e.push(n)}const R3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function z3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,x(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function B3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...z3(n)];return{level:R3[n.kind],line:bc(e,i)}}const V3=()=>{},H3=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),U3={ansi:e=>({ok:!0,output:sj(e)}),frame:e=>({ok:!0,frame:e})};function W3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=jo();let i=c.u(e6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=n6(e,i,{by:`feed`,fps:n}),p=U3.ansi(o.body),m=l6(t,o,F3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:U3.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=B3(`render`,s,{kind:`threw`,error:e},A(i,o)),r=H3(e);return{bar:ZA(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:V3,failure:{level:t,line:`frame ${n}`}}}}function G3(e,t,n){let{sessionState:r}=e;return cG(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function K3(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:aG(i.view.source.effective(),Tc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function q3(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return aG(G3(e,n,o.state),s===null||Tc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function J3(e,t,n){L3(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;L3(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:Bn(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const Y3=e=>Vn(Bn(e,e.hints));function X3(e,t,n,r,i){J3(t,r,i),L3(i,{encoding:t.encoding}),(0,X.runInAction)(()=>{r6(e,t),e.worldStates.take(n),Q3(e,t)[Symbol.dispose]()})}function Z3(e,t){(0,X.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function Q3(e,t){let n=T$(t.requested,e.sessionState,t.hookData.session_id);return e.renderCache.holdSession(n.projectDir,n.cwd,n.target.path,t)}function $3(e,t,n,r){let i=Y3(t);return t6(e,Q3(e,t),t,i,n,r)}function e6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{J3(o,n,r),s=Y3(o)}catch(e){throw a[Symbol.dispose](),e}return t6(e,a,o,s,n,r)}function t6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{hints:l}=n,u={hookData:n.hookData,deps:o,cwd:n.cwd,hints:l};return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:s,view:c,hintsError:r,payloadInputs:u,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function n6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.payload(),C=b.source.effective(),w=b.source.failure(),T=aG(C,S.tmux!==void 0);L3(g,{lanes:Ub.filter(e=>T[e]).join(`,`)||`-`});let ee=b.source.hints(),te=S.term.cols;L3(g,{width:String(te)});let E=_c(r,_,h,n.by),ne=E.kind===`held`||E.kind===`owed`?E.error:null,D=o.notice({sessionId:_,dismissed:r.get(_,BF),enabled:C.updateNotice}),re=iV(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Un(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(ne?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:lV(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...Bc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...w===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${w}`}]],de={config:y.config},fe=MB(_,n.by,ae,[...D.offer,...re],[...D.failure,...ue.map(e=>({about:e.kind,text:e.message,copy:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),pe=b.source.facts(),me={diagnostics:HB(fe),drawing:n,feeds:i.feedsOf(_,h),today:kX(pe.builtins.today,h)},he=ko(S.metrics)?void 0:S.metrics;L3(g,TX([...b.state.sources.keys()],b.registry.runSources(),pe)),L3(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:rX(S.git),feeds:A3(me.feeds)});let ge=[],_e=eX(C,te),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=D3(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:ye}),we=PB(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te);f.observe(_,h,be.rows.some(e=>e.kind===`menu`),C.menuTimeout);let De=f.since(_,h);L3(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:te,rows:WB(ee.termRows,n.by===`feed`?Ub.flatMap(e=>{let t=Hb[e].rows;return T[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=UB(r.get(_,Bi),fe),je=Ae===null?be:YA(be,GB(fe,Ae,_,n.by,ke)),Me=u.gitProvider.getStats(),k=u.usageStore.getStats(),Ne=ve.lastFrame(),Pe=Ne.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Fe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,A=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ie=[...D.failure.map(()=>`update-failed`),...[...ue,...ge].map(A)].join(`,`)||`-`;return L3(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${k.size}/${k.hits}h/${k.misses}m`,effect:Ne.effect,effectT:Ne.t.toFixed(3),speed:`${Ne.speed}x`,effectRows:`${Ne.made}made/${Ne.reused}reused`,effectOwn:Pe,fadeBasis:Ne.basis,stateRev:String(Ne.revision),fades:Fe(Ne.fades),leaves:Fe(Ne.leaves),motion:je.motion,evaluated:String(xe),cellBreaks:String(Se),pending:je.pending.join(`,`)||`-`,rules:[...Ce].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:E.kind===`none`?`-`:E.kind,pipeEvent:ce?.hold??`-`,upd:String(D.offer.length),ask:String(re.length),warn:Ie,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:xe,cellBreaks:Se,clickShown:ne,pipeShown:le,delivered:Ee,lanes:T}}function r6(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,GG,o);let s=T1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,WG,s)}function i6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(a6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function a6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:T$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:Oj(t.hookData)}}function o6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:a6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function s6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u($3(e,t,n,i));i6(e,t,aG(l.view.source.effective(),Tc(t.hints.tmux)));let u=o.monotonic(),d=r-u;L3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await FJ(t=>bX(l.payloadInputs,n,f,()=>e.worldStates.of(l.sessionId),()=>l.view.registry.namedRuns().values(),t),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();L3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:dX(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=n6(e,l,Gb),b=t.hookData.session_id,S=F3(y,s.following(b)),C=Aj(t.hints.client??null)===`statusline`,w=C?l6(b,h,S):h.body;return L3(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{frame:w,delivered:c6(e,b,v,g,_)}}catch(e){a.e=e}finally{a.d()}}function c6(e,t,n,r,i){return()=>{n(),r!==null&&pee(e.sessionState,t,r),i!==null&&e.launcher.answeredPipeEvent(i)}}function l6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:YA(t.body,KB(I3(e,[r,...i]),t.diagnostics,e,t.geometry))}const u6=e=>{};function d6(e,t,n=``){let r=H3(t);return{outcome:{kind:`threw`,error:t},resp:{...r,error:`renderer ${e.name}: ${n}${r.error}`},seen:`failed`,settled:u6}}function f6(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&E.isAbsolute(t)&&{location:eB(t)}}}}function p6(e,t){e.push(...t.kind===`answered`?t.output.record:t.record)}async function m6(e,t,n,r,i,a,o,s){let c=f6(r),l=(t,r)=>void e.deliver({kind:`event`,at:Ue(n),event:{kind:`effect-done`,session:t.session,of:t.id,outcome:r===null?{kind:`ok`}:{kind:`failed`,reason:r}}},[[`effect`,String(t.id)]]),u=t.requested(c),d=await e.answer({kind:`event`,at:a,event:{kind:`config`,context:c,worldState:u}});if(p6(s,d),d.kind===`threw`)return L3(s,{renderer:e.name}),d6(e,d.error,`its config turn: `);let f=await e.answer({kind:`event`,at:a,event:{kind:`request`,id:i,context:c,waitEndsAt:o}});if(p6(s,f),f.kind===`threw`)return L3(s,{renderer:e.name}),d6(e,f.error);let{effects:p}=f.output;L3(s,{renderer:e.name,effects:p.map(e=>`${e.kind}:${e.surface}`).join(`,`)||`-`});let m=null;for(let e of p)switch(e.kind){case`present`:e.request===i?m===null?m=e:l(e,`a second statusline frame for request ${i}`):l(e,`presents request ${e.request}, not this turn's ${i}`);break}if(m===null)return d6(e,Error(`presented no statusline frame for request ${i}`));let h=m,g=n.monotonic(),_;try{_=U3[c.encoding](h.frame)}catch(t){return l(h,`encoding its frame threw: ${H3(t).error}`),d6(e,t,`its frame could not be encoded: `)}return L3(s,{encoded:`${A(n,g)}ms`}),{outcome:{kind:`ok`},resp:_,seen:h.frame.motion,settled:e=>l(h,e?null:`the client did not take the answer`)}}const h6=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`]),g6=[[`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`]],_6=[[`workspace.added_dirs`,`string-list`]];function v6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of g6){let i=x6(n,e);if(i==null)t.missingRequired.push(e);else{let n=y6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of _6){let i=x6(n,e),a=i===void 0?r:b6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))h6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function y6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function b6(e){return Array.isArray(e)&&e.every(e=>y6(e)===`string`)?`string-list`:y6(e)}function x6(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 S6(e,t,n){let{tokens:r}=S({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&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:mA(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function C6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ln.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ln.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function w6(e,t,n,r){let{report:i}=v6(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=eq(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!re(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=C6(e.encoding);s.ok||a.push(s.problem);let c=pr(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=zn(e),{configFile:u,refusedArgs:d}=S6(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:Mj(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:_A(u,l.configEnv)},refusedArgs:d}}}function T6(e,t){switch(e){case`vars`:return{what:e,vars:E6(t)};case`segments`:return{what:e,segments:j6(t)};case`config`:return{what:e,config:F6(t)}}}function E6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=k6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=D6(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:O6(r.lastUpdatedMs(),t.clock)})}return o}function D6(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};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`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function O6(e,t){return e===null?null:Math.max(0,t.now()-e)}function k6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,A6(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}`,A6(i));return t}function A6(e){return e.kind}function j6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=N6(n),o=M6(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:P6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function M6(e){let t=new Map;for(let n of mS(e.presets))for(let r of Uy(_S(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=zy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function N6(e){let t=[],n=new Set;for(let r of Uy(nS(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 P6(e,t,n){let r=new Set([...PR(e,t).keys()].flatMap(e=>XR(e,n)));return Array.from(r).sort()}function F6(e){return e===null?null:e.config}const I6=[`vars`,`segments`,`config`];function L6(e){return typeof e==`string`&&I6.includes(e)}const R6=e=>({resp:e,exitAfterFlush:null,settled:u6}),z6=e=>({kind:`reply`,...e}),B6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},V6=(e,t)=>z6(R6({ok:!1,error:t,code:e,daemonV:3}));function H6(e){let t=eq(e.sessionId);if(!t.ok)return V6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return V6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Ub.join(`, `)}): it predates the lane toggles — update it`);let n=Xb(e.lane);return n===null?V6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Ub.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function U6(e,t,n,r,i){if(t.kind===`url`)return z6(R6(await Z6(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?V6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?H6(a):typeof a.kind!=`string`||!Object.hasOwn(B6,a.kind)?V6(`BAD_REQUEST`,`unknown kind`):z6(await W6(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,settled:u6})}async function W6(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,effectSessions:m,menuIdle:h,journalTurns:g,sessionState:_,tmuxStatusLines:v,watcherRegistry:y,limits:b,handlerProbes:S,renderSightings:C,bundle:w,sourceDigest:T,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,settled:u6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return R6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return R6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:G6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,collector:e.collector.stats(),effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:_.size(),observers:_.observers(),revision:_.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:v.stats(),watchersActive:y.size(),dirWatchesActive:y.dirWatches(),nextRestartReason:b.describeNextRestart(),handlerProbes:S.list(),clients:C.list(Ve(new Date(o.now()))),bundle:w,sourceDigest:T,daemon:b.serving(),doctorStores:LZ(ee)})});if(t.kind===`render`){let c=new Date(o.now()),l=Ve(c),u=o.monotonic(),d=Fe(r.at,u),f=[];a.requestsTotal++;let p=r.id,m=w6(t,a,e.log,e.home),h=(t,n)=>C.see(t.hookData.session_id,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Xo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Nj(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.hookData.session_id,m.req,p));let g=t=>{t.outcome.kind!==`ok`&&a.requestsErrored++,L3(f,{req:String(r.id),timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:s,line:c}=B3(`render`,f,t.outcome,A(o,u));return e.log(s,c),{resp:t.resp,exitAfterFlush:null,settled:t.settled}};if(!m.ok)return g(r8(m.problems));let _=await m6(e.renderer,e.collector,o,m.req,p,l,u+mr(m.req.deadline,r.at,{epochMs:c.getTime(),monoMs:u}),f).catch(e=>({outcome:{kind:`threw`,error:e},resp:H3(e),seen:`failed`,settled:u6}));try{return h(m.req,_.seen),g(_)}catch(e){throw _.settled(!1),e}}if(t.kind===`click`)return R6(await Y6(e,r,n,i,(n,r)=>X6(e,t,n,r)));if(t.kind===`debug`){if(!L6(t.what))return R6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${I6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?J6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Dx(`colorCompatibility`)):q6};return R6({ok:!0,debug:T6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function G6(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const K6={endcaps:Dx(`endcaps`),colorCompatibility:Dx(`colorCompatibility`),wrap:Dx(`autoWrap`),padding:Dx(`padding`),width:1/0},q6=new Map;function J6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Ej(i,{...K6,colorCompatibility:t}));return n}async function Y6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`req`,String(t.id)],[`queued`,`${Fe(t.at,o)}ms`]],c=await i(s,()=>n()||r());L3(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=B3(`click`,s,c,A(a,o));return e.log(l,u),t8(c)}async function X6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};L3(n,{via:`cli`});let{verb:a,value:o}=t;return typeof a!=`string`||typeof o!=`string`?{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof a} and ${typeof o}`]}:Q6(()=>e8(e,a,o,i,n,r))}async function Z6(e,t,n,r,i){return Y6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(L3(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Xn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Xn].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o=ja(a);if(!o.ok)return{kind:`bad-request`,problems:[o.problem]};let s={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return Q6(()=>e8(e,o.verb,o.value,s,n,r))})}async function Q6(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof qG?{kind:`closing`,error:e}:e instanceof JG?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const $6={link:`verb`,"tmux-status":`linkVerb`};async function e8(e,t,n,r,i,a){if(t===`tmux-status-click`)return L3(i,{verb:t}),n8(e,n,i,a);L3(i,{[$6[r.via]]:t});let o=m1(t,n);o===null?L3(i,{sid:`-`}):o.ok&&(L3(i,{sid:o.id}),e.collector.clicked(o.id));let s=await e.renderer.answer({kind:`event`,at:Ue(e.clock),event:{kind:`click`,verb:t,value:n,session:o,arrival:r,gone:a}});switch(s.kind){case`answered`:return i.push(...s.output.record),{kind:`ok`};case`threw`:throw i.push(...s.record),s.error}}function t8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:return H3(e.error)}}async function n8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(L3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=ja(s.url);return t.ok?t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):e8(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await u$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,s$,e.tmp),{kind:`ok`}}const r8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},settled:u6});function i8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return E.join(e,`update-act`,n)}const a8={kind:`idle`};function o8(e){if(e===null)return a8;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const s8=e=>({stdout:E.join(e,`stdout`),stderr:E.join(e,`stderr`),status:E.join(e,`status`)}),c8=e=>E.join(e,`record.json`);function l8(e){let t;try{t=s.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function u8(e){let t=qo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function d8(e,t){let n=E.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(E.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const f8=e=>e.now()-o.uptime()*1e3;async function p8(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function m8(e){try{return JSON.parse(s.readFileSync(c8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const h8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function g8(e,t,n,r){let i=null;async function a(a){let o=E.join(e,String(a)),c=m8(o);if(c===null)return null;if((i===null||!h8(i.record,c))&&(i={record:c,ours:await p8(c,t,n,f8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=s8(o),u=kt(l.status),d=u===null?null:u8(l.stderr)??u8(l.stdout);if(!s.existsSync(o))return null;let f={act:a,record:c,alive:i.ours,end:u,lastLine:d};return f.alive||(i.final=f),f}return{async read(){let t=null;for(;;){let n=l8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${E.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function _8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(E.join(e,`.claim-`));try{return s.writeFileSync(c8(r),JSON.stringify(n)),s.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{s.rmSync(r,{recursive:!0,force:!0})}}async function v8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=E.join(t,String(c)),u=e.launchJobSync(i,s8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!_8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return y8;if(l8(t).some(e=>e>c))return d8(t,c),y8;d=!0}finally{d?u.release():u.withdraw()}for(let e of l8(t).filter(e=>e<c))d8(t,e);return{ok:!0,act:c}}const y8={ok:!1,reason:`another act claimed this bundle first`};function b8(e,t,n){let r=s8(E.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function x8(e,t,n){if(t.kind===`pending`)return Oo(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}var S8=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function C8(e){return e.kind===`source`?e.newer.digest:cs(e.newer)}const w8=e=>`${e.version} [${en(e.digest)}]`;function T8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:w8(e.newer),running:w8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:cs(e.newer),running:cs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${us}@${cs(e.newer)}`,`install`]}}}}const E8={offer:[],failure:[]};function D8(e,t,n){if(e===null)return E8;let r=C8(e);if(!n.enabled||n.dismissed===r)return E8;let i=T8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?jB(`[${i.busy}]`,null):jB(`[${i.act}]`,Ta([{verb:ca,args:[n.sessionId]}])),c=[jB(a,null),s,jB(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,BF,r]}])),jB(`[disable]`,Ta([{verb:Xi,args:[n.sessionId,VF,`false`]},{verb:Wi,args:[n.sessionId,HF,`false`]}]))];return{offer:[{severity:DB,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function O8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return k8(t)}}function k8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function A8(e){switch(e.kind){case`current`:return[`info`,`build: current ${w8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${w8(e.source)}, running ${w8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function j8(e){switch(e.kind){case`current`:return[`info`,`release: current ${cs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${cs(e.latest)}, running ${cs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${cs(e.installed)}, latest ${cs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function M8(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,gates:f,onApplied:p,log:m}=e,h=Oo(`unread`),g=Oo(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new qG(`apply-update`);return t},v=g8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new S8,w=e=>C.run(`acts`,e),T=!1,ee=[],te=(e,t)=>{ee.push(n.every(t,e,{unref:!0}))},E=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function ne(){let e=E(),t=e===null?null:C8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(BF,[t])})}function D(){let e=T?I:O8(h,g),r=x8(t.get(),e,Ue(n));(0,X.runInAction)(()=>t.set(r)),ne()}function re(){let e=sn(a,()=>rn(o));return h=F(e),x(A8(e)),D(),e}async function ie(){let e=fs(tn,await ds(us,d,u,n));g=F(e),S(j8(e)),D()}let O=null,ae=Ne(m);async function oe(e){try{let t=await e();return O=null,{ok:!0,value:t}}catch(e){return e instanceof qG?{ok:!1,error:e.message}:(O=`update act files (${s}): ${e.message}`,ae([`error`,O]),{ok:!1,error:O})}}function se(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=b8(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;m(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function ce(){let e=await oe(async()=>{let e=await v.read();return T||se(e),e});if(T||!e.ok)return;let t=o8(e.value);y===null&&t.kind===`running`&&m(`info`,`apply-update: act ${t.act} is running; watching it`),y?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(m(`info`,`apply-update: act ${t.act} succeeded`),re(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await w(ce),!T&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=re();te(re,c),ee.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),te(()=>void ie(),l))},close(){T=!0,D(),ee.forEach(e=>e())},notice:e=>D8(E(),y??a8,e),running:()=>w(async()=>{let e=await oe(()=>v.read());return e.ok&&o8(e.value).kind===`running`}),error:()=>O,act:()=>w(async()=>{if(T)throw new qG(`apply-update`);let e=await oe(()=>v.read());if(T)throw new qG(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=E();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=T8(t),a=e.value;if(o8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await v8(r,s,a===null?null:a.act,C8(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new Z(`apply-update: ${o.reason}`);m(`info`,`apply-update: act ${o.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),y={kind:`running`,act:o.act}})}}function N8(){return X.observable.box(Oo(`unread`),{deep:!1})}function P8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function F8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function I8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:P8(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=P8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!F8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var L8=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}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 R8=`pass`,z8={okMs:5*6e4,failedMs:45e3},B8=z8.okMs;function V8({failures:e}){return NY(z8,e,B8)}function H8(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function U8(e){return`git:${e}`}function W8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:E.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Ac(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${jc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function G8(e){return e.kind===`ok`?e.value.branch:void 0}function K8(e){e.missed=!0,MJ(e,`unread`)}function q8(e,t){return e.missed&&e.reading.get().kind===`pending`&&jJ(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function J8({value:e,pr:t}){let n=PJ(e);return n.kind===`ok`?F({...n.value,pullRequest:PJ(t)}):n}const Y8=L(`git cache closed`,`read`);function X8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Z8=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.forgeLookups=new Ao(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new uY(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new hV({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return IJ(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>J8(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:Y8};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}built(e){let t={period:new PY(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:I,reading:kJ(),inFlight:null},n={root:e,refresh:new L8,watch:this.followWatch(e,null).watch,period:new PY(()=>{n.refresh.share(R8,()=>this.refreshPass(n))},this.clock),value:{reading:kJ(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=W8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(R8,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e){return e.holders++,e.value.missed&&(K8(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(R8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(U8(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch(X8(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,jJ(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of $q(i.value))o.add(e);let s=G8(i),c=s===void 0?q8(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,H8(n),o.size===0?F(null):L([...o].join(`; `),`read`),A(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(X8(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(K8(r),`owed`):(MJ(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,jJ(r,a.outcome),r.period.landed(V8(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch(X8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,A(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(jJ(t,i),t.period.landed(V8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);NJ(e.value,t),NJ(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},Q8=class{static usageDir(e){return E.join(e,`usage`)}static locksDir(e){return E.join(e,`locks`)}static isLocked(e,t){let n=E.join(this.locksDir(e),t);if(!s.existsSync(n))return!1;try{let e=s.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),s.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),s.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=E.join(this.locksDir(e),n),a=t.monotonic(),o=String(process.pid);for(;t.monotonic()-a<r;)try{return await s.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await Le(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=E.join(this.locksDir(e),t);try{await s.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([s.promises.mkdir(e,{recursive:!0}),s.promises.mkdir(this.usageDir(e),{recursive:!0}),s.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=E.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await Le(t,75);continue}try{let e=await s.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await Le(t,75)}}return k(`Failed to read ${n} 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,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=E.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},c=JSON.stringify(o);await s.promises.writeFile(a,c,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const $8={"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 e5=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(e,t){let n=t.now()-1440*60*1e3;return await Q8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await Q8.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){k(`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)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys($8).length} models`),this.executionCache=$8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys($8).length} models`),$8)}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,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}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,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}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`}},t5=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 n5(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 r5={okMs:60*1e3,failedMs:10*1e3},i5={calculatedCost:null,tokens:null,tokenBreakdown:null};function a5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function o5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const s5={entries:0,cost:0,breakdown:o5(),days:new Map};async function c5(e,t,n,r){let i=zJ(new Date(a5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await e5.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=zJ(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...LJ};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function l5(e){let t=0,n=0,r=o5(),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)??{...LJ};RJ(n,t),i.set(e,n)}}if(t===0)return{usage:i5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{usage:{calculatedCost:n,tokens:a,tokenBreakdown:r},days:i}}function u5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function d5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!u5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...LJ};RJ(r,t),n.set(e,r)}return Object.fromEntries(n)}async function f5(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))}function p5(e,t){(0,X.runInAction)(()=>e.set(t))}var m5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new t5;scans;daySets=new Map;speedFlight=new t5;requestFlight=new t5;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new uY(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new IY({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??r5,watch:FY,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async()=>{let e=await r().record;return e.kind===`failed`?e:F(e.kind===`ok`?e.value.usage:i5)},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e){let t=this.sessions.get(e);if(t===void 0)return Oo(`unread`);let n=t.failure.get();return n===null?F(t.record?.usage??i5):L(n,`read`)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.monotonic(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,A(this.clock,i)),p5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}declareToday(e,t){if(this.closed)return IJ(L(`usage store closed`,`read`));let n=qJ(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||u5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}async observed(e,t,n){let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return p5(this.hold(e).speed,t),t;let r=n5(t.kind===`ok`?t.value.usage.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return p5(this.hold(e).speed,s),s})}speedOf(e){return this.sessions.get(e)?.speed.get()??Oo(`unread`)}async ingest(e,t,n,r){let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,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)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,usage:s.value.usage,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>ie(e,`projects`)+O),i={roots:r,sums:new O1(`today over ${e.join(`,`)}`,()=>d5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await XJ(e,D(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of aY(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 oY(e,r,s5,(e,t)=>c5(e,t,un(this.host),this.clock));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 aY(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...l5(i),mainStamp:a})}async scan(e){try{let t=a5(this.clock.now()),n=await JJ(e),r=[];for(let e of n){let n=await YJ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await YJ(Lo(n));if(a===void 0||a.mtimeMs<t)continue;let o=eq(i.slice(0,-6));if(!o.ok){this.log(`warn`,`usageStore scan: transcript ${JSON.stringify(i)} names no session: session id ${o.problem}`);continue}r.push({sessionId:o.id,path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await f5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=zJ(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}};const h5={command:null,todos:[],pending:[],done:[]};function g5(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 _5(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 v5(e,t){if(t.isSidechain)return e;let n=_5(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=g5(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 y5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>g5(e,t.name),[]),done:e.done}}var b5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new cY(h5,v5,(e.ledger??new uY(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return x5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:x5(e,t)}};function x5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(y5(t.value))}const S5=3e4;var C5=class{names;constructor(e){let t=e.logger??Pe;this.names=new IY({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>w5(e.launcher,t),every:()=>({okMs:S5,failedMs:S5}),watch:FY,maxEntries:64,logger:t,ledger:e.ledger??new uY(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function w5(e,t){let n=await pc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const T5=6e4,E5={okMs:T5,failedMs:T5};function D5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function O5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var k5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>E5,watch:FY,maxEntries:1,logger:t,ledger:e.ledger??new uY(t),clock:e.clock};this.name=new IY({...n,name:`host.name`,read:()=>O5(`name`,()=>D5(o.hostname()))}),this.user=new IY({...n,name:`host.user`,read:()=>O5(`user`,()=>o.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},A5=class{known=new sY(64);refreshes;constructor(e,t=Pe,n=new uY(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=j5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.monotonic(),i=PN(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function j5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const M5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function N5(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}var P5=class{known=new sY(256);refreshes;constructor(e,t=Pe,n=new uY(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oo(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n){let r=this.clock.monotonic(),i=await F5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,A(this.clock,r)),i}};async function F5(e){let t=await I5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function I5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=L5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function L5(e,t){let n=e.toString(`utf8`).split(`
|
|
484
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!M5.test(t))continue;let r=N5(t);if(r!=null)return r}return null}const R5=e=>oz(e),z5=e=>E.join(e.storage.folder,R5(e.sessionId)),B5=e=>JSON.stringify([e.folder,e.generation]),V5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var H5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Dc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new IY({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(z5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:FY,maxEntries:256,logger:e.logger,ledger:e.ledger??new uY(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{s.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!Oc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(B5(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${B5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(B5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=B5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>V5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(E.join(n.folder,E.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(z5(e)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&Oc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>V5(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>V5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(B5(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=zc(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=z5(e),r;try{r=await s.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=UY(r);return i.kind===`failed`?L(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${A(this.clock,t)}ms`;try{let t=await s.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=E.join(e.folder,a.name);try{let{mtimeMs:r}=await s.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&R5(t.sessionId)===a.name);if(r>=n||o)continue;await s.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function U5(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new k5({clock:n,logger:r,ledger:i}),gitProvider:new Z8({inner:new DJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new m5({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new mY({clock:n,logger:r,ledger:i}),metricsProvider:new wY({clock:n,logger:r,ledger:i}),activityProvider:new b5({clock:n,logger:r,ledger:i}),tmuxService:new C5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new A5(n,r,i),cacheExpiry:new P5(n,r,i),managedStorage:new H5({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),sourceRuns:e.sourceRuns,faults:new AY,log:e.logger,clock:n}}function*W5(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*fne(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);yield*Object.values(t.partials??{})}for(let t of mS(e.presets)){for(let n of Uy(_S(e,t).node))n.when!==void 0&&(yield n.when);let n=bS(e,t);for(let e of oy){let t=n[e];sy(t)&&(yield t)}}for(let[,t]of W5(e))for(let[,e]of Qy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of qF(t))yield e}function pne(e,t,n){let r=OU(t),i=new Set,a=new Set,o=new Set;for(let e of fne(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of RR(e,t.helpers))a.add(n);for(let n of WR(e,t.helpers))o.add(n)}for(let[,e]of W5(t))for(let{reaches:t}of r.ofVariable(e))for(let e of t)i.add(e);let s=new Set(a);for(let e of a){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)s.add(e)}let c=new Set,l=new Set(n);for(let e of s){let n=t.actions[e];if(n!==void 0&&(`set`in n&&c.add(n.set),`insertSegment`in n&&l.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)l.add(e)}for(let e of mS(t.presets))for(let n of Uy(_S(t,e).node))n.kind===`segment`&&l.add(n.name);let u=(e,t)=>i.has(e)||t.kind===`state`&&c.has(t.key),d=e=>[...e].filter(e=>!Ii(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(W5(e));return[...f(`variable`,p.keys(),e=>u(e,p.get(e))),...f(`action`,Object.keys(e.actions??{}),e=>s.has(e)),...f(`helper`,Object.keys(e.helpers??{}),e=>o.has(e)),...f(`segment`,Object.keys(e.segments??{}),e=>l.has(e))]}function mne(e){return Math.floor(Math.max(e/4,e*Br-67108864))}const hne={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function G5(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=e.name===void 0?void 0:n.variables[az(vk(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[vk(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>yk(e)(t)&&t!==az(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${yA(e,`<default>`)}: projections=${[...MU(n).keys()].join(`,`)||`-`} instantSegments=${v3(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e.path} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}const gne=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},K5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${gne(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function _ne(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(K5(t))} state=${n} files=${R(yA(e.configLayers,`<bundled default>`))} awaiting=${r(e.repos.awaiting)} declined=${r(e.repos.declined)} unproven=${e.repos.unproven.length===0?`-`:JSON.stringify(e.repos.unproven)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function vne(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function q5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function yne(e,t){return new Set(mS(e.presets).filter(n=>_S(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function bne(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,E.join(e.projectDir,zz)])];return cV({named:[...dB(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:a})}function xne(e){return e.filter(Boolean).join(`
|
|
485
|
+
`)||null}const J5=e=>e instanceof Error?e.message:String(e);function Y5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Sne(e){let{loaded:t,chain:n}=e;return W1({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:Y5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...Y5(t.installed),checkout:t.installed.checkout,roots:t.installed.roots,unreached:t.installed.unreached},config:t.config,dropped:t.dropped.map(e=>e.message),placed:null},sources:[...e.sources].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.folder,t.generation])})}function Cne(e,t){let n=new Map,r=new Map;for(let[i,a]of Object.entries(e.variables)){if(a.kind!==`source`)continue;let e=n.get(a.storage)??t.keyFor(a.storage);n.set(a.storage,e),r.set(i,e)}return r}function X5(e,t,n){let r=[];try{let i=DW(t.locs,t.layers,$W,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Cne(i.config,n)};return{kind:`resolved`,...a,key:Sne(a),warnings:r}}catch(e){return e instanceof fb&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function Z5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??$W,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new R1(t.clock),m=new r0(p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=f3(o,m,n,t.compile??d3(t.signer),Tne),f.push(...h.loadWarnings);let r=m.view();f.push(...h3(o,r,n,t7)),r.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof fb&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:yne(l,u),fileHeldSettings:AG(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>pne(e.raw,i.placed,d)).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},sources:e.sources}}}function Q5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:A(i,e.started)},o=t=>xne([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:J5(r.cause),cause:r.cause}}}function wne(e,t,n,r,i=null){let a=X5(t,n,r.storage);if(a.kind===`failed`)return Q5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:Z5(a,r);return Q5(e,n,a.warnings,o,r.clock)}function $5(e,t,n,r,i=null){let a=r.clock.monotonic(),o=hB(r.locations,tV(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return wne({repos:s,advisories:[SB(r.locations,e,t),bB(o),cB(s)],started:a},t,c,r,i)}function e7(e,t,n){let r=X5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:Z5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${J5(i.cause)}`,{cause:i.cause});return i.state}const Tne=new Set([`directory`]),t7=new Set([`view`]);function Ene(e,t,n,{source:r,changed:i,log:a}){let o=n.hookData.session_id,s=e.registry.view();h3(e.config,s,t,t7);let c=X.observable.box(n,{deep:!1}),l;try{l=r({sessionId:o,state:e,store:s.variableStore,requested:()=>c.get()})}catch(e){throw s.dispose(),e}z4(e.compiled,s.variableStore,s,l);let u=(0,X.reaction)(()=>[l.payload(),l.selections(),s.published(),e.registry.published()],()=>i(o),{equals:X.compareShallow,fireImmediately:!0,onError:e=>a(`error`,`session view change threw sid=${JSON.stringify(o)}: ${String(e)}`)});return{sessionId:o,state:e,store:s.variableStore,registry:s,source:l,requested:e=>{e!==c.get()&&(0,X.runInAction)(()=>c.set(e))},facts:()=>c.get(),lastRenderCellsBySegment:new Map,retire:u,dispose:()=>(u(),s.dispose())}}const Dne=({state:e,registry:t})=>[...[...e.sources].map(([e,t])=>({kind:`plugin`,source:e,storage:t})),...t.subscriptions().map(e=>({kind:`run`,run:e}))];var One=class{entries=new Map;answersWatch;closed=!1;due=new Map;walk=null;holds=new Map;views=new Map;copies=new Map;viewHolds=new Map;pins=new Map;openFailures=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??Pe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},s.mkdirSync($B(e.stateDir),{recursive:!0});let{dir:n,name:r}=aV(eV(e.stateDir));this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??_3(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=q5(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n,null);a.state!==null&&this.log(`info`,G5(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??e7(t,a.repos.plugins,this.deps),watch: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=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++;let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=jo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(q5(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let i=n.hookData.session_id,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o;try{o=this.opened(e,t,n,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),o}opened(e,t,n,r){let i=n.hookData.session_id,a;try{a=Ene(t,e.cwd,n,{source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(i,{error:e,facts:n}),e}return this.openFailures.delete(i),this.views.set(i,a),this.viewHolds.set(a,{entry:e,holders:0,retired:null}),this.log(`info`,`session view opened sid=${JSON.stringify(i)} by=${r} cwd=${e.cwd} views=${this.views.size}`),a}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),this.views.has(e.sessionId)||this.copies.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}retireSession(e){this.openFailures.delete(e);let t=this.views.get(e);t!==void 0&&this.retireView(t,`idle`)}subscriptions(){return{sources:new Map([...this.views].map(([e,t])=>[e,Dne(t)]))}}close(){if(this.closed)return;this.closed=!0,this.walk?.(),this.walk=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n,r){if(this.closed)throw Error(`render cache used after close`);return $5(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.due.delete(t),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,due:this.due.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Fr(this.accountedBytes())}/${Fr(this.budgetBytes())}MB`)}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,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,vne(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){this.due.delete(e);let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,G5(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state),this.retire(r,`reload`,{entry:e,state:i.state})),this.fit(e),this.refreshWatcher(e,i),this.observers.onReload?.(e,n,t,i.kind)}reloadEvery(e){for(let t of this.entries.values())this.due.set(t,e);this.armWalk()}armWalk(){this.walk!==null||this.due.size===0||(this.walk=this.deps.clock.defer(()=>this.walkOne()))}walkOne(){this.walk=null;let e=null;for(let t of this.entries.values()){let n=this.due.get(t);n!==void 0&&(e=[t,n])}if(e===null)return;let[t,n]=e;try{this.reloadInto(t,n)}catch(e){this.log(`error`,`every-entry reload threw projectDir=${R(t.projectDir)} cwd=${R(t.cwd)} configFile=${R(t.configFile??`-`)} cause=${R(K5(n))}: ${x(e)}`)}finally{this.armWalk()}}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=bne(e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const kne=e=>!aq(e)&&!SN(e)&&e!==`update.dismissed`&&e!==Bi;var Ane=class{past=X.observable.map(void 0,{deep:!1});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:ZK(e,kne,(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 Z(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.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){(0,X.runInAction)(()=>{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)})}},n7=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};const r7=(e,t)=>e.kind===`ok`?F(t(e.value)):e;function jne(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest}}const i7=(e,t)=>{let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>Object.is(n,Reflect.get(t,e)))};function Mne({pullRequest:e,...t}){return t}function a7(e,t,n,r,i){let{lanes:a}=n,o=(e,t)=>x8(e,t,i),s=e?.builtins,c={session:o(s?.session,a.usage),today:o(s?.today,n.today),speed:o(s?.speed,a.speed),context:o(s?.context,a.context),metrics:o(s?.metrics,a.metrics),activity:o(s?.activity,a.activity),cache:o(s?.cache,a.cache),autocompact:o(s?.autocompact,a.autoCompact),git:o(s?.git,r7(a.git,Mne)),pr:o(s?.pr,jne(a.git)),tmux:o(s?.tmux,r7(a.tmuxSession,e=>({session:e}))),hostName:o(s?.hostName,a.hostName),hostUser:o(s?.hostUser,a.hostUser)},l=Object.fromEntries([...a.sources].map(([t,n])=>[t,o(e?.sources[t],n)])),u=Object.fromEntries([...a.runs].map(([t,{reading:n,fault:r}])=>{let i=e?.runs[t],a=o(i?.reading,n);return[t,i!==void 0&&i.reading===a&&i.fault===r?i:{reading:a,fault:r}]})),d={builtins:c,sources:l,runs:u,update:r,diagnostics:n.faults};return e!==void 0&&i7(c,e.builtins)&&i7(l,e.sources)&&i7(u,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:2,session:t,seq:e===void 0?1:e.seq+1,...d}}function o7(e,t){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason===t?e:{...e,seq:e.seq+1,diagnostics:[...e.diagnostics.filter(e=>e.kind!==`stamp`),{kind:`stamp`,reason:t}]}}function s7(e){return e.diagnostics.find(e=>e.kind===`stamp`)?.reason??null}const Nne=e=>({hookData:e.hookData,cwd:e.cwd,hints:e.hints}),Pne=e=>({plugins:new Map(e.flatMap(e=>e.kind===`plugin`?[[e.source,e.storage]]:[])),runs:new Map(e.flatMap(e=>e.kind===`run`?[[e.run.digest,e.run]]:[]))}),Fne=(e,t)=>e.plugins.size===t.plugins.size&&[...e.plugins].every(([e,n])=>{let r=t.plugins.get(e);return r!==void 0&&V5(n,r)})&&e.runs.size===t.runs.size&&[...e.runs.keys()].every(e=>t.runs.has(e));function c7({stop:e,holds:t}){e(),t.close()}var Ine=class{records=new Map;stopSweep=null;constructor(e){this.deps=e}requested(e){let t=Nne(e),n=e.hookData.session_id,r=(0,X.runInAction)(()=>{let e=this.records.get(n);if(e===void 0){let e=this.open(n,t);return this.records.set(n,e),e.stamped.document}e.active=!0;let{phase:r}=e;r.kind===`live`&&r.declared.set(this.declared({...e,locator:t},r.holds));let i=r.kind===`live`?r:this.live(e,t);return e.phase=i,this.stamp(e,i.inputs.get()),e.stamped.document});return this.armSweep(),r}clicked(e){let t=this.records.get(e);t?.phase.kind===`live`&&(t.active=!0)}subscribed({sources:e}){for(let t of e.keys())this.records.has(t)||this.deps.log(`error`,`subscriptions name session ${JSON.stringify(t)}, which the collector has no record of`);(0,X.runInAction)(()=>{for(let t of this.records.values()){let n=Pne(e.get(t.session)??[]);if(Fne(n,t.subscriptions))continue;t.subscriptions=n;let{phase:r}=t;r.kind===`live`&&r.declared.set(this.declared({...t,locator:r.declared.get().locator},r.holds))}})}holding(e){let t=this.records.get(e);return t?.phase.kind===`live`?(t.turns++,()=>{t.turns--}):()=>{}}sweep(){for(let e of this.records.values())e.phase.kind===`live`&&(e.active?e.active=!1:e.turns===0&&!this.deps.watched(e.session)&&this.retire(e,e.phase))}stats(){let e=[...this.records.values()];return{sessions:e.length,retiring:e.filter(e=>e.phase.kind===`retiring`).length}}close(){this.disarmSweep();for(let{phase:e}of this.records.values())e.kind===`live`&&c7(e);this.records.clear()}open(e,t){let n={plugins:new Map,runs:new Map},r=this.reader({session:e,locator:t,subscriptions:n}),i=r.inputs.get(),a;try{if(i.kind===`failed`)throw Error(i.reason);a=a7(void 0,e,i.readings,i.update,Ue(this.deps.clock))}catch(e){throw r.holds.close(),e}let o={document:a,from:i};return{session:e,stamped:o,subscriptions:n,active:!0,turns:0,phase:this.watch(e,o,r)}}live(e,t){return this.watch(e.session,e.stamped,this.reader({...e,locator:t}))}reader(e){let t=new n7,n=X.observable.box(this.declared(e,t),{deep:!1});return{holds:t,declared:n,inputs:(0,X.computed)(()=>this.read(n.get()))}}watch(e,t,n){let r=(0,X.reaction)(()=>n.inputs.get(),n=>(0,X.runInAction)(()=>{n!==t.from&&this.stamp({session:e,stamped:t},n)&&this.deps.deliver({kind:`world-state`,worldState:t.document})}),{onError:t=>this.deps.log(`error`,`world state stamp threw sid=${JSON.stringify(e)}: ${x(t)}`)});return{kind:`live`,...n,stop:r}}declared({session:e,locator:t,subscriptions:n},r){let i=JSON.stringify(e);try{let{result:{lanes:e,faults:a},acquired:o,released:s}=r.declare(()=>hX(this.deps.owners,r,t,n));for(let e of a)this.deps.log(`error`,`session declaration threw sid=${i} ${e}`);return o+s>0&&this.deps.log(`info`,`session declared sid=${i} acquired=${o} released=${s} held=${r.size}`),{locator:t,lanes:e}}catch(e){return this.deps.log(`error`,`session declaration threw sid=${i}: ${x(e)}`),{locator:t,lanes:pX(L(`session declaration threw: ${String(e)}`,`read`),n)}}}inputsOf(e){return{...e,deps:this.deps.owners}}read({locator:e,lanes:t}){try{return{kind:`read`,readings:gX(this.inputsOf(e),t),update:this.deps.update()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}}stamp({session:e,stamped:t},n){let r=t.document,i=n.kind===`failed`?o7(r,n.reason):this.assembled(r,n,Ue(this.deps.clock)),a=i===r?null:s7(i);return a!==null&&this.deps.log(`error`,`world state sid=${JSON.stringify(e)}: ${a}`),t.document=i,t.from=n,i!==r}assembled(e,t,n){try{return a7(e,e.session,t.readings,t.update,n)}catch(t){return o7(e,`stamping the world state: ${String(t)}`)}}retire(e,t){c7(t);let n={kind:`retiring`};e.phase=n,this.deps.log(`info`,`session retired sid=${JSON.stringify(e.session)}`),this.deps.deliver({kind:`retire`,session:e.session}).then(()=>{e.phase===n&&this.records.get(e.session)===e&&this.records.delete(e.session),this.records.size===0&&this.disarmSweep()})}armSweep(){this.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.sweep(),{unref:!0}))}disarmSweep(){this.stopSweep?.(),this.stopSweep=null}},Lne=class{documents=X.observable.map(void 0,{deep:!1});take(e){let t=this.documents.get(e.session);if(t!==void 0&&e.seq<=t.seq){if(e.seq===t.seq&&(0,X.compareStructural)(e,t))return;throw Error(`world state seq ${e.seq} for session ${JSON.stringify(e.session)} does not follow the held seq ${t.seq}`)}(0,X.runInAction)(()=>this.documents.set(e.session,e))}of(e){let t=this.documents.get(e);if(t===void 0)throw Error(`no world state for session ${JSON.stringify(e)}: the host hands one in with the config ahead of every request`);return t}drop(e){(0,X.runInAction)(()=>this.documents.delete(e))}};function Rne(e){return({sessionId:t,state:n,store:r,requested:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>cG(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n}=i();return{hookData:t,hints:n,home:e.home}}),c=r.derive(`session.draw`,`computed`,()=>({sources:[...n.sources.keys()],effective:o.read(),configFacts:{...jG(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),l=()=>e.worldStates.of(t),u=r.derive(`session.payload`,`computed`,()=>CX(l(),s.read(),c.read()));return{session:t,payload:()=>u.read(),effective:()=>c.read().effective,facts:l,run:e=>l().runs[e]??jY,hints:()=>s.read().hints,failure:()=>s7(l()),selections:()=>c.read().effective}}}const l7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,u7=`#{session_id} #{client_control_mode} #{pane_id}`;function d7(e){let t=new Set;for(let n of e.split(`
|
|
486
|
+
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function f7(e,t){let n=new Set;for(let r of e.split(`
|
|
487
|
+
`)){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 zne(e,t){let n=new Map;for(let t of e.split(`
|
|
488
488
|
`)){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(`
|
|
489
|
-
`)){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
|
|
490
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
491
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=I7(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,[M7(`@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)} ${y7} 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,Zne(n));if(r===null||this.closed)return null;let i=Qne(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,S7(r),e])}),i!==n.status){let e=Jne(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,v7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,Xne(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,L7(n));if(i===null)return;let a=R7(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,z7);if(r===null||this.closed)return;let i=B7(r[0]??``);if(n.kind===`none`&&H7(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`&&H7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...b7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${D7(`${this.deps.handler} ${ere(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,z7);if(r===null)return;let i=U7(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,r){let i=U7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.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,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,E7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,E7(n),r)))}};function nre(e){try{return wa(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),rre={"--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":W7(`none`),"--background":W7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":W7(`optional`),"-c":W7(`none`),"--continue":W7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":W7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":W7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":W7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":W7(`optional`),"-h":W7(`none`),"--help":W7(`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":W7(`none`),"--print":W7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":W7(`optional`),"--resume":W7(`optional`),"--safe-mode":$(`none`),"--session-id":W7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":W7(`optional`),"--tmux":W7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":W7(`none`),"--version":W7(`none`),"-w":W7(`optional`),"--worktree":W7(`optional`)},ire={resume:`--resume`,fresh:`--session-id`};function are(e){return[ire[e.kind],e.sessionId]}const G7=e=>e.startsWith(`-`)&&e!==`-`;function K7(e,t){let n=q7(t);return n===null?{dir:e??t,args:[]}:e!==null&&ore(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const ore=(e,t)=>e===t||e.startsWith(t+E.sep);function sre(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!G7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=rre[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=>!G7(e)):o.arity===`variadic`?cre(n.slice(r),e=>!G7(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 q7(e){let t=e.split(E.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(E.sep),repo:t.slice(0,n-1).join(E.sep)||E.sep}}function cre(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,lre=E.join(`bin`,`cc-candybar-native`),ure=DN(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=QQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const dre={band:{on:async(e,t,n)=>{let r=nn(t.bundle);if(r===null)throw new Z(`${Ub.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=E.join(r,lre);if(!n.fileExists(i))throw new Z(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${J7} from ${r}`,finished:fre(e,r,n)}},off:async()=>Y7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=X7(e),i=j(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${Ub.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:hre(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>Y7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=X7(e),i=await n.barPanes(r);return i.length>0?Y7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Y7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=QQ(e.hints.tmux);if(r.kind===`refused`)return Y7(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return Y7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>Y7(`the daemon draws ${X7(e).pane}'s bar in its status line`),off:async()=>Y7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function fre(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,J7],r);let i=await $Q(n.claudeInput,e.hints.tmux,ure);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 ${J7} from ${t} and typed /reload-plugins into ${i.pane}`}const pre=new Set([Jo,hA]);function mre(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function hre(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,Wt(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}) — ${Ub.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=bre(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Ub.statusline.label} off and on again`);let s=gre(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=sre(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=mre(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])=>pre.has(e)),m=(e,t)=>qt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...are(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=_re(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(K7(null,i.cwd),_))}let y=m(K7(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await 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}\`, ${vre[g.kind](e.sessionId)}, and its statusline follows lane B`}function gre(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 _re(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const vre={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},yre={"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 bre(e){let t=qQ(e);return t.kind===`ready`?XQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:JQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:yre[t.kind]}var xre=class{owed=new Map;setups=new C8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Wb.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),hc(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await dre[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};const Sre=[`request`,`feed`],Z7=new WeakMap;let Cre=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Cre++;return Z7.set(e,n),n};var wre=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get($7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Q7(n.config),i=[];for(let n of Sre){let a=this.records.get($7(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=$7(e,t);this.records.delete(a),this.records.set(a,{generation:Q7(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const $7=(e,t)=>`${t}\0${e}`;var Tre=class{queue=new C8;sessions=new C8;gathers=new C8;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new YG(e);let a=this.deps.monotonic();t(Fe(i,a)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(A(this.deps,c)),this.refuseClosed(e),i())throw new YG(e);let t=this.deps.monotonic(),l=await o();a(A(this.deps,t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:A(this.deps,e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new JG(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},e9=class extends Error{constructor(e,t,n){super(t instanceof Error?t.message:String(t)),this.record=e,this.thrown=t,this.subscriptions=n,this.name=`TurnThrew`}};function Ere(e,t,n,r,i){let a=async e=>{try{let t=await n.answer(e);if(i(t.subscriptions),e.event.kind!==`request`)for(let n of t.effects)o(n,`a ${e.event.kind} turn answers no request`);return{kind:`answered`,output:t}}catch(e){return e instanceof e9?(i(e.subscriptions),{kind:`threw`,error:e.thrown,record:e.record}):{kind:`threw`,error:e,record:[]}}},o=(e,n)=>void c({kind:`event`,at:Ue(t),event:{kind:`effect-done`,of:e.id,outcome:{kind:`failed`,reason:n}}},[[`sid`,e.session],[`effect`,String(e.id)]]),s=(t,n,i)=>{let a=[[`renderer`,e],[`input`,t.event.kind],...n];switch(i.kind){case`answered`:i.output.record.length>0&&r(`info`,bc(`turn`,[...a,...i.output.record]));return;case`threw`:r(`error`,bc(`turn`,[...a,...i.record,[`error`,x(i.error)]]))}},c=async(e,t)=>{let n=await a(e);return s(e,t,n),n};return{name:e,answer:a,deliver:c}}async function Dre({verbs:e,menuIdle:t},{verb:n,value:r,session:i,arrival:a,gone:o},s){let c=e.handler(n);if(c===void 0)throw new Z(`unknown click verb: ${n}`);let l=i?.ok?i.id:null;l!==null&&t.clickArrived(l);try{await c(r,{arrival:a,placeWaited:e=>R3(s,{placeWait:`${e}ms`}),gatherTook:e=>R3(s,{gather:`${e}ms`}),turnWaited:e=>R3(s,{turnWait:`${e}ms`}),clientGone:o})}finally{l!==null&&t.clickSettled(l)}}function Ore(e){let t=new Map,n=0,r=(t,n)=>({effects:t,subscriptions:e.renderCache.subscriptions(),record:n}),i=async(i,a,o)=>{switch(i.kind){case`config`:return Z3(e,i.context,i.worldState,a,o),r([],o);case`request`:{let{frame:s,delivered:c}=await c6(e,i.context,a,i.waitEndsAt,o),l=++n;return t.set(l,c),r([{kind:`present`,id:l,session:i.context.hookData.session_id,surface:`statusline`,request:i.id,frame:s}],o)}case`world-state`:return e.worldStates.take(i.worldState),r([],o);case`retire`:return Q3(e,i.session),r([],o);case`effect-done`:{let e=t.get(i.of);if(e===void 0)throw Error(`effect-done for effect ${i.of}, which is not a present on its way`);return t.delete(i.of),i.outcome.kind===`ok`&&e(),r([],o)}case`click`:return await Dre(e,i,o),r([],o);case`menu-idle`:return await e.verbs.closeIdle(i.session,i.idle),r([],o)}};return{answer:async({event:t,at:n})=>{let r=[];try{return await i(t,n,r)}catch(t){throw new e9(r,t,e.renderCache.subscriptions())}}}}function kre(e){return{handler:t=>{let n=w1.get(t);return n&&((t,r)=>n(t,{...e,...r}))},closeIdle:(t,n)=>T1(t,n,e)}}async function Are(e,t,n,r){let i=await e.answer({kind:`event`,at:t(),event:{kind:`menu-idle`,session:n,idle:r}});if(i.kind===`threw`)throw i.error}var jre=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?nx(t.since,t.timeoutS):null;t.timer?.at!==n&&(this.disarm(t),n!==null&&(t.timer={at:n,clear:this.deps.clock.after(Math.max(0,(n-this.deps.now())*1e3),()=>this.fire(e),{unref:!0})}))}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};function Mre(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=En(c),u=()=>Ve(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new gQ(i),h=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,now:u,observeWarnings:e=>{e.kind===`launch-pipes`?p(`warn`,e.text):p(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),pe.wakeWhere(`data`,()=>!0)}}),g=e.probe(h),_=e.storage(p),v=new eq(_.session),y=new uq(v,p,_.history),b=Wr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),S=new MQ,C=new Fj,w=e.doctorStores,T=new gV({clock:i,counters:m,logger:p}),ee=new dY(p),te=new Lc({watchers:T,logger:p,clock:i}),E=new $Y({launcher:h,clock:i,logger:p,ledger:ee,watchers:T,fileEvents:te}),ne=W5({launcher:h,host:c,watchers:T,fileEvents:te,clock:i,logger:p,ledger:ee,sourceRuns:E}),{gitProvider:D,usageStore:re,tmuxService:ie,hostService:O,managedStorage:ae}=ne,oe=new kne,se=new PA,ce=new jre({clock:i,now:u,close:(e,t)=>Are(Ee.renderer,u,e,t),failed:(e,t)=>p(t instanceof JG?`info`:`error`,`menu-idle: close failed (session=${e}): ${x(t)}`)}),le=e.linkSigner,ue=new Cc({supersede:(e,t)=>ae.supersede(e,t),launch:h.launch,state:v,log:p,now:u,clock:i}),de=new xre({edge:e.laneEdge(h,e=>pe.following(e),d.signal,g),host:{bundle:t.path,node:t.node,socket:o.socket,preload:Cs(t.path,c)},state:v,log:p,now:u,defer:e=>void i.defer(e)}),fe=new tre({edge:{run:(e,t,n)=>pc(h,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>pe.subscribe(e,t),sessionInPane:(e,t)=>pe.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Vt(o.socket)}`,...[...t.node,t.path].map(Vt),`url-handle`].join(` `),owner:o.socket,log:p}),pe=new F3({render:(e,t,n)=>G3(Ee,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>v.revision(e),t),lanes:e=>q3(Ee,e),pin:e=>{let t=ye.pin(e);return()=>{ye.stopDrawing(e,`feed`),t()}},shown:e=>me.shown(e.hints.tmux),watching:()=>me.follow(),refreshes:()=>ee.totals(),periods:k3,clock:i,instant:u,log:p}),me=new zne({clock:i,listPanes:e=>pc(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,u7]),listClients:e=>pc(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,d7]),sockets:()=>new Set(pe.watched().flatMap(({req:e})=>he(e))),onAnswer:(e,t)=>fe.answered(e,t),onChange:e=>pe.wakeWhere(`visibility`,t=>he(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function he({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ge=new wre,_e=P8(),ve=new Ine,ye=new Dne({clock:i,stateDir:o.state,locations:l,env:c.env,sessionState:v,watchers:T,log:p,storage:ae,signer:le,gates:s,source:Lne({sessionState:v,worldStates:ve,home:c.home,history:e=>y.depth(e),navigation:(e,t)=>oe.depth(e,v,s.state.gateFor(t))})},{budgetBytes:()=>pne(n),observers:{onReload:(e,t,n,r)=>{p(`info`,gne(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`)}});te.subscribe(e=>{switch(e.kind){case`period`:T.judge();return;case`caught-up`:ye.reloadEvery({kind:`events-resumed`,since:e.since}),pe.wakeWhere(`data`,()=>!0);return;case`moved`:pe.wakeWhere(`data`,()=>!0);return}});let be=60*1e3,xe=L8({clock:i,targets:t.targets,intervalMs:be,stat:e.stat,held:()=>Se.running(),exit:()=>a(0),log:p}),Se=N8({fact:_e,clock:i,launcher:h,probe:g,entryUrl:t.entryUrl,digest:t.digest,actsDir:a8(o.state,t.path),intervalMs:be,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>xe.checkNow(),log:p}),Ce=new Tre({log:p,monotonic:()=>i.monotonic()}),we={gates:s,sessionState:v,stateDir:o.state,locations:l,journalTurns:Ce,clickLanded:e=>ce.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>Se.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];ye.reload(...t,{kind:`doctor`});let n=ye.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:w,probes:S,clients:C,bundle:t.path,serving:()=>b.serving(),claudeInput:e.claudeInput(h),history:y,navigation:oe,configFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>ye.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:le,runs:ue,lanes:{of:(e,t)=>J3(Ee,e,t),clicked:(e,t,n)=>s6(Ee,e,t,n)},views:{follow:(e,t)=>ye.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>ye.drawnCopy(e,t,n)},Te=new Fne({owners:ne,update:()=>_e.get(),clock:i,watched:e=>pe.feedOpen(e),deliver:e=>Ee.renderer.deliver({kind:`event`,event:e,at:u()},[[`sid`,e.kind===`world-state`?e.worldState.session:e.session]]),log:p}),Ee={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:w,stats:m,handlerProbes:S,renderSightings:C,watcherRegistry:T,refreshLedger:ee,fileEvents:te,payloadProviders:ne,sessionState:v,effectSessions:se,menuIdle:ce,journalTurns:Ce,linkSigner:le,runs:ue,sourceRuns:E,laneSetups:de,tmuxStatusLines:fe,frameFeeds:pe,renderWarnings:ge,renderCache:ye,updateWatch:Se,limits:b,collector:Te,worldStates:ve,renderer:Ere(`main`,i,Ore({clock:i,log:p,sessionState:v,renderCache:ye,payloadProviders:ne,worldStates:ve,linkSigner:le,renderWarnings:ge,effectSessions:se,frameFeeds:pe,updateWatch:Se,fileEvents:te,menuIdle:ce,launcher:h,laneSetups:de,tmuxStatusLines:fe,verbs:kre(we)}),p,e=>Te.subscribed(e))};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),W6(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),G6(Ee,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),we.reloadConfig(e)},arm(){d.signal.throwIfAborted(),te.start(o.watchProbe),xe.arm(),Se.arm(),b.arm()},close(e){let t=[[`journalTurns close`,()=>Ce.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>pe.close()],[`menuIdle dispose`,()=>ce.dispose()],[`updateWatch close`,()=>Se.close()],[`binaryWatch close`,()=>xe.close()],[`limits disarm`,()=>b.disarm()],[`collector close`,()=>Te.close()],[`renderCache close`,()=>ye.close()],[`gitService close`,()=>D.close()],[`usageStore close`,()=>re.close()],[`tmuxService close`,()=>ie.close()],[`hostService close`,()=>O.close()],[`runs close`,()=>ue.close()],[`sourceRuns close`,()=>E.close()],[`managedStorage close`,()=>ae.close()],[`fileEvents close`,()=>te.close()],[`watcherRegistry close`,()=>T.closeAll()],[`sessionState close`,()=>v.close()]];for(let[e,n]of t)try{n()}catch(t){p(`warn`,`${e} failed: ${t.message}`)}return f=!0,h.settled()}}}function Nre(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 Pre=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Pe){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e=new Map,t;try{t=s.readFileSync(this.filePath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${n}); starting empty`),e}try{let n=JSON.parse(t);return Nre(n)?nq(n,(e,t)=>this.logger(`warn`,`session-state load: dropped session key ${JSON.stringify(e)}: session id ${t}`)):(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),e)}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),e}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=A(this.clock,n);try{await s.promises.mkdir(E.dirname(this.filePath),{recursive:!0});let o=await s.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await s.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await s.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${A(this.clock,n)}ms held=${a}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.clearTimer?.(),this.clearTimer=null,this.pending===null)return;let e=this.pending,t=this.clock.monotonic();try{s.mkdirSync(E.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);s.writeFileSync(n,r,{mode:384}),s.chmodSync(n,384),s.rmSync(this.writingPath,{force:!0}),s.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,A(this.clock,t)),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${A(this.clock,n)}ms held=${r}ms`)}};function Fre(e,t,n){return{session:new Pre(e.sessionState,n,500,t),history:jq(e.settingsHistory,t)}}function t9(e,t,n){for(let r of(t??``).split(E.delimiter)){if(!E.isAbsolute(r))continue;let t=E.join(r,e);if(n(t))return t}return null}function n9(e,t){try{return s.accessSync(e,t),s.statSync(e).isFile()}catch{return!1}}function Ire(e){try{return s.realpathSync(e)}catch{return E.resolve(e)}}function Lre(e,t,n){let r=t9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:E.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 r9=2e3;async function i9(e,t,n,r){let i=await pc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function a9(e,t){if(t.ok)return t.stdout;let n=Xe(t,t.stdout);throw Error(`${e} failed (${Ze(t)}${n===``?``:`: ${n}`})`)}function Rre(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 zre=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Bre(e,t){return e.split(`
|
|
492
|
-
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return
|
|
493
|
-
`);async function Wre(e,t){if(process.platform===`linux`)return{executable:await s.promises.readlink(`/proc/${t}/exe`),argv:(await s.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await s.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=a9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Ure,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function o9(e,t,n){return a9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function s9(e,t){let n=await pc(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await o9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Gre(e,t){let{panePid:n,cwd:r,foreground:i}=await s9(e,t),a=await o9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Wre(e,i),c=Kq(a).get(i)?.ppid;if(c===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await s.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:c,fromShell:i!==n,attached:Hre(a,i,n)}}function Kre(e,t,n,r,i){let a=e=>Le(r,e,n);return{claudeInput:i$(e),barPanes:async t=>Bre(await i9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await i9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await i9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void a9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Nq(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:GF,paneClaude:t=>Gre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+r9;for(;;){let o=await s9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${r9/1e3} s`);await a(100)}},launcherNode:e=>Lre(e,e=>n9(e,s.constants.X_OK),Ire),onPath:(e,t)=>{let n=t9(e,t,e=>n9(e,s.constants.X_OK));return n===null?null:s.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?Rre(i.stdout):null;return a===null?(a9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();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=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(100)}return!0},typeShellLine:async(t,n)=>void await i9(e,t,n$(t.pane,`cc-candybar-lane`,[]),n)}}const qre=/^[0-9a-f]{64}$/;function c9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Jre(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>c9(e,t).toString(`hex`),verify:(t,n)=>qre.test(n)?ue(Buffer.from(n,`hex`),c9(e,t)):!1}}function l9(e){return E.join(e,`link.key`)}function u9(e){let t,n=()=>t??=Yre(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Yre(e){let t;try{t=s.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Xre(e),t=s.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Jre(t)}function Xre(e){s.mkdirSync(E.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;s.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{s.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{s.unlinkSync(t)}}function Zre(e,t,n){return{daemonLog:t,launcher:e=>It(e,n),storage:t=>Fre(e,t,n),doctorStores:LZ(e.state),doctorEdge:YZ,claudeInput:i$,probe:qs,laneEdge:(e,t,r,i)=>Kre(e,t,r,n,i),linkSigner:u9(l9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Xr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:s.statSync}}const Qre=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function d9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Qre[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const $re={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};function eie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=d9(t),o=d9(n),s={};for(let e of r){let t=$re[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function tie(e){return{ok:!0,band:e.rows.map(e=>lj(e).map(eie))}}function nie(e){return QA(tie,e)}const rie={band:e=>JSON.stringify(nie(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:h7(e)})};function f9(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)}}}function iie(e,t){t.allowHalfOpen=!1;let n=e.stats.accept();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(er(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3,request:n.id},null,d6)}),u=nr(r=>{let i=Zn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{if(!c){e.kind===`reply`&&e.settled(!1);return}e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.settled):d(e.sessionId,e.lane)}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(U3(t),null,d6)}).finally(()=>{c||(l(),a())})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,d6)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=f9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(tr(rie[i](e,t))),refused:e=>t.end(er(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const p9=`CC_CANDYBAR_PARENT_PID`;function aie(e){let t=e[p9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${p9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function oie(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let m9=null,h9=null,g9=null,_9=null;function v9(){if(_9===null)throw Error(`runDaemon has not started`);return _9}function y9(e,t){v9().log.log(e,t)}function sie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:an(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function cie(e){let n=N(e.host);_9={world:e,paths:n,log:new dee(n.log,e.clock)},t.on(`uncaughtException`,e=>{y9(`error`,`uncaughtException: ${e.stack||e.message}`),C9(1)}),t.on(`unhandledRejection`,e=>{y9(`error`,`unhandledRejection: ${String(e)}`),C9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{y9(`info`,`received ${e}, shutting down`),C9(0)});lie().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${x(e)}`),C9(1)}async function lie(){let{world:e,paths:n,log:r}=v9(),{host:i}=e,a=Ir(i.env);m9=await Ys(t.pid,qs(e.launcher).startTime);let o=await tc(rc(e,m9,n.registry));if(!o.decision.allow){y9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),C9(1);return}h9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),hn(n.socket);let c=Mre({...Zre(n,r,e.clock),bundle:sie(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:WF(),exit:C9});g9=c,oie({clock:e.clock,anchor:aie(i.env),probe:qs(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,de.createServer(e=>iie(c,e)),n.socket,!1)}function x9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){y9(`error`,`server error: ${a.message}`),C9(1);return}if(i){y9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}uie(e,n,r).catch(b9)}),n.listen(r,()=>die(e,r))}async function uie(e,n,r){let i=await Rs(zs(gn(r)),(t,n)=>Js(t,n,qs(e.launcher)));if(i.kind===`attach-and-exit`){y9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}y9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){y9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),C9(1);return}}x9(e,n,r,!0)}function die(e,n){let r=Hs(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}pie(n);try{s.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Fr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Fr(e.memoryLimitBytes)}MB`),ai(v9().paths.spawnBackoff),e.arm(),fie(n,r.identity)}function fie(e,n){Gs({bound:n,myPid:t.pid,readIdentity:()=>Hs(e),readLease:()=>zs(gn(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function pie(e){let n=Bs(gn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const mie=e=>(t,n,r)=>fee(e,{socket:t},`tmux-status`,n,r);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(mie(v9().world.launcher)),Vs(v9().paths.lease,t.pid),h9!==null&&nc(h9,t.pid,$s,e=>s.unlinkSync(e)),t.exit(e))}const hie={connectMs:200,budgetMs:500};async function gie(e,t,n){return _ie(t,await vie(e,t),n.includes(`--json`))}function _ie(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
494
|
-
`:
|
|
495
|
-
`;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?``:` ${
|
|
489
|
+
`)){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 Bne=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`:this.loop.clear(),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: ${x(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,clear:this.deps.clock.after(this.deps.intervalMs,()=>this.ask(),{unref:!0})};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:f7(t.stdout,d7(n.stdout)),status:zne(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),!Vne(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 Vne(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))}function Hne(e){return`ccb`+oe(`sha256`).update(e).digest(`hex`).slice(0,12)}const Une=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function p7(e){if(e===void 0)return`terminal`;let t=H.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case V.STANDARD:{let e=t.number===void 0?void 0:Une[t.number];if(e!==void 0)return e;break}case V.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case V.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case V.DEFAULT:case V.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const Wne={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};function Gne(e){return e.replaceAll(`#`,`##`)}function Kne({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=Wne[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${p7(e)}`,`bg=${p7(t)}`,...r].join(`,`)}]`}function qne(e){let t={},n=e=>{let n=Kne(e)+Gne(e.text);if(e.link===void 0)return n;let r=Hne(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>lj(e).map(n).join(``)),links:t}}function m7(e){return QA(qne,e)}const h7=Hb.tmuxStatus.rows,g7=`@cc-candybar-status-prior`,_7=`@cc-candybar-status-wrote`,v7=`@cc-candybar-binding-prior`,y7=[`-T`,`root`,`MouseDown1Status`],b7=Array.from({length:h7},(e,t)=>t),x7=e=>`@cc-candybar-row-${e}`,Jne=e=>`#[fill=terminal]#{${x7(e)}}`,S7=e=>`status-format[${e}]`;function Yne(e){return e===0?`off`:e===1?`on`:String(e)}function C7(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 Xne(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 w7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function T7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function E7(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function Zne(e){return e.map(e=>e.map(E7).join(` `)).join(` ; `)}const D7=`ccb:separator`;function O7(e){return T7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,D7],e]))}function k7(e,t){let n=e.split(`${D7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const A7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],j7=e=>[`show-options`,`-g`,`-q`,`-v`,e],M7=e=>[[`show-options`,`-t`,e],A7(e,`status`),...b7.map(t=>A7(e,S7(t)))];function N7(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
490
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of b7)i.includes(S7(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 P7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,S7(Number(t)),w7(n)])]}const Qne=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...M7(e),...b7.map(e=>j7(S7(e))),A7(e,g7),A7(e,_7)];function F7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:C7(t)}catch(e){return{kind:`theirs`,why:`${g7} 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 $ne(e,t,n){let[r=``,...i]=t,a=N7(i.slice(0,2+h7)),o=i.slice(2+h7,2+2*h7),[s=``,c=``]=i.slice(2+2*h7);if(s!==``)return F7(s,c,n);let l=C7(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:h7-l},(e,t)=>[l+t,Jne(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,g7,JSON.stringify(f)],...P7(e,d)]}}const I7=e=>[...M7(e),A7(e,_7)];function L7(e,t,n){let r=N7(n.slice(0,2+h7)),i=n[2+h7]??``,a=[],o=[];if(Xne(r.formats,t.wrote))a.push(...P7(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,S7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,w7(t.status)]):o.push(`status`)),a.push(...b7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,x7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,g7],[`set-option`,`-q`,`-u`,`-t`,e,_7]),{commands:a,kept:o}}const ere=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,R7=[[`list-keys`,`-T`,`root`]];function z7(e){let t=ere.exec(e);return t===null?null:{line:t[0],command:t[1]}}const B7=`cc-candybar://tmux-status-click/`,tre=e=>`${B7}${Ca([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,V7=e=>e?.command.includes(B7)??!1;function H7(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,v7]};return V7(z7(t))?{steps:[e===null?{command:[`unbind-key`,...y7]}:{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 nre=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)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=m7(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(e){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[t,n]of this.servers){for(let[r,i]of[...n.layouts]){n.layouts.delete(r);let a=this.askSync(e,t,I7(r));if(a===null)continue;let o=L7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}let r=n.binding;if(n.binding={kind:`none`},r.kind===`ours`||r.kind===`adopted`){let n=this.askSync(e,t,R7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=rre(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}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,h7-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#{${g7}}\t#{${_7}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
491
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=F7(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,[j7(`@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)} ${v7} 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,Qne(n));if(r===null||this.closed)return null;let i=$ne(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,x7(r),e])}),i!==n.status){let e=Yne(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,_7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,Zne(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,I7(n));if(i===null)return;let a=L7(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,R7);if(r===null||this.closed)return;let i=z7(r[0]??``);if(n.kind===`none`&&V7(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`&&V7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...y7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${E7(`${this.deps.handler} ${tre(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,R7);if(r===null)return;let i=H7(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,r){let i=H7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.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,O7(t));return n.kind===`ok`?k7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,O7(n)));return r.kind===`ok`?k7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,T7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,T7(n),r)))}};function rre(e){try{return wa(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),U7=e=>({arity:e,keep:!1}),ire={"--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":U7(`none`),"--background":U7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":U7(`optional`),"-c":U7(`none`),"--continue":U7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":U7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":U7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":U7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":U7(`optional`),"-h":U7(`none`),"--help":U7(`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":U7(`none`),"--print":U7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":U7(`optional`),"--resume":U7(`optional`),"--safe-mode":$(`none`),"--session-id":U7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":U7(`optional`),"--tmux":U7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":U7(`none`),"--version":U7(`none`),"-w":U7(`optional`),"--worktree":U7(`optional`)},are={resume:`--resume`,fresh:`--session-id`};function ore(e){return[are[e.kind],e.sessionId]}const W7=e=>e.startsWith(`-`)&&e!==`-`;function G7(e,t){let n=K7(t);return n===null?{dir:e??t,args:[]}:e!==null&&sre(e,n.top)?{dir:e,args:[]}:{dir:e===null||K7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const sre=(e,t)=>e===t||e.startsWith(t+E.sep);function cre(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!W7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=ire[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=>!W7(e)):o.arity===`variadic`?lre(n.slice(r),e=>!W7(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 K7(e){let t=e.split(E.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(E.sep),repo:t.slice(0,n-1).join(E.sep)||E.sep}}function lre(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const q7=`candybar-band@cc-candybar`,ure=E.join(`bin`,`cc-candybar-native`),dre=DN(`/reload-plugins`),J7=e=>({kind:`done`,said:e});function Y7(e){let t=ZQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const fre={band:{on:async(e,t,n)=>{let r=nn(t.bundle);if(r===null)throw new Z(`${Hb.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=E.join(r,ure);if(!n.fileExists(i))throw new Z(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${q7} from ${r}`,finished:pre(e,r,n)}},off:async()=>J7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=Y7(e),i=j(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${Hb.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:gre(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>J7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=Y7(e),i=await n.barPanes(r);return i.length>0?J7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):J7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=ZQ(e.hints.tmux);if(r.kind===`refused`)return J7(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return J7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>J7(`the daemon draws ${Y7(e).pane}'s bar in its status line`),off:async()=>J7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function pre(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,q7],r);let i=await QQ(n.claudeInput,e.hints.tmux,dre);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 ${q7} from ${t} and typed /reload-plugins into ${i.pane}`}const mre=new Set([Jo,hA]);function hre(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function gre(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,Wt(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}) — ${Hb.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=xre(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Hb.statusline.label} off and on again`);let s=_re(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=cre(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=hre(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])=>mre.has(e)),m=(e,t)=>qt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...ore(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=vre(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(G7(null,i.cwd),_))}let y=m(G7(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await 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}\`, ${yre[g.kind](e.sessionId)}, and its statusline follows lane B`}function _re(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 vre(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const yre={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},bre={"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 xre(e){let t=KQ(e);return t.kind===`ready`?YQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:qQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:bre[t.kind]}var Sre=class{owed=new Map;setups=new S8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Ub.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),hc(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await fre[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};const Cre=[`request`,`feed`],X7=new WeakMap;let wre=0;const Z7=e=>{let t=X7.get(e);if(t!==void 0)return t;let n=wre++;return X7.set(e,n),n};var Tre=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(Q7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Z7(n.config),i=[];for(let n of Cre){let a=this.records.get(Q7(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=Q7(e,t);this.records.delete(a),this.records.set(a,{generation:Z7(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const Q7=(e,t)=>`${t}\0${e}`;var Ere=class{queue=new S8;sessions=new S8;gathers=new S8;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new JG(e);let a=this.deps.monotonic();t(Fe(i,a)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(A(this.deps,c)),this.refuseClosed(e),i())throw new JG(e);let t=this.deps.monotonic(),l=await o();a(A(this.deps,t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:A(this.deps,e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new qG(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},$7=class extends Error{constructor(e,t,n){super(t instanceof Error?t.message:String(t)),this.record=e,this.thrown=t,this.subscriptions=n,this.name=`TurnThrew`}};function Dre(e,t,n,r,i){let a=async e=>{let t=e9(e.event),r=t===null?()=>{}:i.holding(t);try{let t=await n.answer(e);if(i.subscribed(t.subscriptions),e.event.kind!==`request`)for(let n of t.effects)o(n,`a ${e.event.kind} turn answers no request`);return{kind:`answered`,output:t}}catch(e){return e instanceof $7?(i.subscribed(e.subscriptions),{kind:`threw`,error:e.thrown,record:e.record}):{kind:`threw`,error:e,record:[]}}finally{r()}},o=(e,n)=>void c({kind:`event`,at:Ue(t),event:{kind:`effect-done`,session:e.session,of:e.id,outcome:{kind:`failed`,reason:n}}},[[`effect`,String(e.id)]]),s=(t,n,i)=>{let a=e9(t.event),o=[[`renderer`,e],[`input`,t.event.kind],...a===null?[]:[[`sid`,a]],...n];switch(i.kind){case`answered`:i.output.record.length>0&&r(`info`,bc(`turn`,[...o,...i.output.record]));return;case`threw`:r(`error`,bc(`turn`,[...o,...i.record,[`error`,x(i.error)]]))}},c=async(e,t)=>{let n=await a(e);return s(e,t,n),n};return{name:e,answer:a,deliver:c}}function e9(e){switch(e.kind){case`config`:case`request`:return e.context.hookData.session_id;case`world-state`:return e.worldState.session;case`click`:return e.session?.ok?e.session.id:null;case`retire`:case`effect-done`:case`menu-idle`:return e.session}}async function Ore({verbs:e,menuIdle:t},{verb:n,value:r,session:i,arrival:a,gone:o},s){let c=e.handler(n);if(c===void 0)throw new Z(`unknown click verb: ${n}`);let l=i?.ok?i.id:null;l!==null&&t.clickArrived(l);try{await c(r,{arrival:a,placeWaited:e=>L3(s,{placeWait:`${e}ms`}),gatherTook:e=>L3(s,{gather:`${e}ms`}),turnWaited:e=>L3(s,{turnWait:`${e}ms`}),clientGone:o})}finally{l!==null&&t.clickSettled(l)}}function kre(e){let t=new Map,n=0,r=(t,n)=>({effects:t,subscriptions:e.renderCache.subscriptions(),record:n}),i=async(i,a,o)=>{switch(i.kind){case`config`:return X3(e,i.context,i.worldState,a,o),r([],o);case`request`:{let{frame:s,delivered:c}=await s6(e,i.context,a,i.waitEndsAt,o),l=++n;return t.set(l,c),r([{kind:`present`,id:l,session:i.context.hookData.session_id,surface:`statusline`,request:i.id,frame:s}],o)}case`world-state`:return e.worldStates.take(i.worldState),r([],o);case`retire`:return Z3(e,i.session),r([],o);case`effect-done`:{let e=t.get(i.of);if(e===void 0)throw Error(`effect-done for effect ${i.of}, which is not a present on its way`);return t.delete(i.of),i.outcome.kind===`ok`&&e(),r([],o)}case`click`:return await Ore(e,i,o),r([],o);case`menu-idle`:return await e.verbs.closeIdle(i.session,i.idle),r([],o)}};return{answer:async({event:t,at:n})=>{let r=[];try{return await i(t,n,r)}catch(t){throw new $7(r,t,e.renderCache.subscriptions())}}}}function Are(e){return{handler:t=>{let n=C1.get(t);return n&&((t,r)=>n(t,{...e,...r}))},closeIdle:(t,n)=>w1(t,n,e)}}async function jre(e,t,n,r){let i=await e.answer({kind:`event`,at:t(),event:{kind:`menu-idle`,session:n,idle:r}});if(i.kind===`threw`)throw i.error}var Mre=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?tx(t.since,t.timeoutS):null;t.timer?.at!==n&&(this.disarm(t),n!==null&&(t.timer={at:n,clear:this.deps.clock.after(Math.max(0,(n-this.deps.now())*1e3),()=>this.fire(e),{unref:!0})}))}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};function Nre(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=En(c),u=()=>Ve(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new hQ(i),h=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,now:u,observeWarnings:e=>{e.kind===`launch-pipes`?p(`warn`,e.text):p(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),pe.wakeWhere(`data`,()=>!0)}}),g=e.probe(h),_=e.storage(p),v=new $K(_.session),y=new lq(v,p,_.history),b=Wr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),S=new jQ,C=new Fj,w=e.doctorStores,T=new hV({clock:i,counters:m,logger:p}),ee=new uY(p),te=new Lc({watchers:T,logger:p,clock:i}),E=new QY({launcher:h,clock:i,logger:p,ledger:ee,watchers:T,fileEvents:te}),ne=U5({launcher:h,host:c,watchers:T,fileEvents:te,clock:i,logger:p,ledger:ee,sourceRuns:E}),{gitProvider:D,usageStore:re,tmuxService:ie,hostService:O,managedStorage:ae}=ne,oe=new Ane,se=new PA,ce=new Mre({clock:i,now:u,close:(e,t)=>jre(Ee.renderer,u,e,t),failed:(e,t)=>p(t instanceof qG?`info`:`error`,`menu-idle: close failed (session=${e}): ${x(t)}`)}),le=e.linkSigner,ue=new Cc({supersede:(e,t)=>ae.supersede(e,t),launch:h.launch,state:v,log:p,now:u,clock:i}),de=new Sre({edge:e.laneEdge(h,e=>pe.following(e),d.signal,g),host:{bundle:t.path,node:t.node,socket:o.socket,preload:Cs(t.path,c)},state:v,log:p,now:u,defer:e=>void i.defer(e)}),fe=new nre({edge:{run:(e,t,n)=>pc(h,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>pe.subscribe(e,t),sessionInPane:(e,t)=>pe.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Vt(o.socket)}`,...[...t.node,t.path].map(Vt),`url-handle`].join(` `),owner:o.socket,log:p}),pe=new P3({render:(e,t,n)=>W3(Ee,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>v.revision(e),t),lanes:e=>K3(Ee,e),pin:e=>{let t=ye.pin(e);return()=>{ye.stopDrawing(e,`feed`),t()}},shown:e=>me.shown(e.hints.tmux),watching:()=>me.follow(),refreshes:()=>ee.totals(),periods:O3,clock:i,instant:u,log:p}),me=new Bne({clock:i,listPanes:e=>pc(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,l7]),listClients:e=>pc(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,u7]),sockets:()=>new Set(pe.watched().flatMap(({req:e})=>he(e))),onAnswer:(e,t)=>fe.answered(e,t),onChange:e=>pe.wakeWhere(`visibility`,t=>he(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function he({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ge=new Tre,_e=N8(),ve=new Lne,ye=new One({clock:i,stateDir:o.state,locations:l,env:c.env,sessionState:v,watchers:T,log:p,storage:ae,signer:le,gates:s,source:Rne({sessionState:v,worldStates:ve,home:c.home,history:e=>y.depth(e),navigation:(e,t)=>oe.depth(e,v,s.state.gateFor(t))})},{budgetBytes:()=>mne(n),observers:{onReload:(e,t,n,r)=>{p(`info`,_ne(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`)}});te.subscribe(e=>{switch(e.kind){case`period`:T.judge();return;case`caught-up`:ye.reloadEvery({kind:`events-resumed`,since:e.since}),pe.wakeWhere(`data`,()=>!0);return;case`moved`:pe.wakeWhere(`data`,()=>!0);return}});let be=60*1e3,xe=I8({clock:i,targets:t.targets,intervalMs:be,stat:e.stat,held:()=>Se.running(),exit:()=>a(0),log:p}),Se=M8({fact:_e,clock:i,launcher:h,probe:g,entryUrl:t.entryUrl,digest:t.digest,actsDir:i8(o.state,t.path),intervalMs:be,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>xe.checkNow(),log:p}),Ce=new Ere({log:p,monotonic:()=>i.monotonic()}),we={gates:s,sessionState:v,stateDir:o.state,locations:l,journalTurns:Ce,clickLanded:e=>ce.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>Se.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];ye.reload(...t,{kind:`doctor`});let n=ye.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:w,probes:S,clients:C,bundle:t.path,serving:()=>b.serving(),claudeInput:e.claudeInput(h),history:y,navigation:oe,configFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>ye.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>ye.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:le,runs:ue,lanes:{of:(e,t)=>q3(Ee,e,t),clicked:(e,t,n)=>o6(Ee,e,t,n)},views:{follow:(e,t)=>ye.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>ye.drawnCopy(e,t,n)},Te=new Ine({owners:ne,update:()=>_e.get(),clock:i,watched:e=>pe.feedOpen(e),deliver:e=>Ee.renderer.deliver({kind:`event`,event:e,at:u()},[]),log:p}),Ee={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:w,stats:m,handlerProbes:S,renderSightings:C,watcherRegistry:T,refreshLedger:ee,fileEvents:te,payloadProviders:ne,sessionState:v,effectSessions:se,menuIdle:ce,journalTurns:Ce,linkSigner:le,runs:ue,sourceRuns:E,laneSetups:de,tmuxStatusLines:fe,frameFeeds:pe,renderWarnings:ge,renderCache:ye,updateWatch:Se,limits:b,collector:Te,worldStates:ve,renderer:Dre(`main`,i,kre({clock:i,log:p,sessionState:v,renderCache:ye,payloadProviders:ne,worldStates:ve,linkSigner:le,renderWarnings:ge,effectSessions:se,frameFeeds:pe,updateWatch:Se,fileEvents:te,menuIdle:ce,launcher:h,laneSetups:de,tmuxStatusLines:fe,verbs:Are(we)}),p,Te)};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),U6(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),W6(Ee,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),we.reloadConfig(e)},arm(){d.signal.throwIfAborted(),te.start(o.watchProbe),xe.arm(),Se.arm(),b.arm()},close(e){let t=[[`journalTurns close`,()=>Ce.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>pe.close()],[`menuIdle dispose`,()=>ce.dispose()],[`updateWatch close`,()=>Se.close()],[`binaryWatch close`,()=>xe.close()],[`limits disarm`,()=>b.disarm()],[`collector close`,()=>Te.close()],[`renderCache close`,()=>ye.close()],[`gitService close`,()=>D.close()],[`usageStore close`,()=>re.close()],[`tmuxService close`,()=>ie.close()],[`hostService close`,()=>O.close()],[`runs close`,()=>ue.close()],[`sourceRuns close`,()=>E.close()],[`managedStorage close`,()=>ae.close()],[`fileEvents close`,()=>te.close()],[`watcherRegistry close`,()=>T.closeAll()],[`sessionState close`,()=>v.close()]];for(let[e,n]of t)try{n()}catch(t){p(`warn`,`${e} failed: ${t.message}`)}return f=!0,h.settled()}}}function Pre(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 Fre=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Pe){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e=new Map,t;try{t=s.readFileSync(this.filePath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${n}); starting empty`),e}try{let n=JSON.parse(t);return Pre(n)?tq(n,(e,t)=>this.logger(`warn`,`session-state load: dropped session key ${JSON.stringify(e)}: session id ${t}`)):(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),e)}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),e}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=A(this.clock,n);try{await s.promises.mkdir(E.dirname(this.filePath),{recursive:!0});let o=await s.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await s.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await s.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${A(this.clock,n)}ms held=${a}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.clearTimer?.(),this.clearTimer=null,this.pending===null)return;let e=this.pending,t=this.clock.monotonic();try{s.mkdirSync(E.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);s.writeFileSync(n,r,{mode:384}),s.chmodSync(n,384),s.rmSync(this.writingPath,{force:!0}),s.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,A(this.clock,t)),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${A(this.clock,n)}ms held=${r}ms`)}};function Ire(e,t,n){return{session:new Fre(e.sessionState,n,500,t),history:Aq(e.settingsHistory,t)}}function t9(e,t,n){for(let r of(t??``).split(E.delimiter)){if(!E.isAbsolute(r))continue;let t=E.join(r,e);if(n(t))return t}return null}function n9(e,t){try{return s.accessSync(e,t),s.statSync(e).isFile()}catch{return!1}}function Lre(e){try{return s.realpathSync(e)}catch{return E.resolve(e)}}function Rre(e,t,n){let r=t9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:E.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 r9=2e3;async function i9(e,t,n,r){let i=await pc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function a9(e,t){if(t.ok)return t.stdout;let n=Xe(t,t.stdout);throw Error(`${e} failed (${Ze(t)}${n===``?``:`: ${n}`})`)}function zre(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 Bre=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Vre(e,t){return e.split(`
|
|
492
|
+
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return Bre.exec(r.join(` `))?.[1]===t?[n]:[]})}const Hre=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Ure(e,t,n){for(let r of Kq(Gq(e),t)){if(r.command.split(` `).some(e=>Hre.test(e)))return!0;if(r.pid===n)return!1}return!1}const Wre=[`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(`
|
|
493
|
+
`);async function Gre(e,t){if(process.platform===`linux`)return{executable:await s.promises.readlink(`/proc/${t}/exe`),argv:(await s.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await s.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=a9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Wre,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function o9(e,t,n){return a9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function s9(e,t){let n=await pc(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await o9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Kre(e,t){let{panePid:n,cwd:r,foreground:i}=await s9(e,t),a=await o9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Gre(e,i),c=Gq(a).get(i)?.ppid;if(c===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await s.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:c,fromShell:i!==n,attached:Ure(a,i,n)}}function qre(e,t,n,r,i){let a=e=>Le(r,e,n);return{claudeInput:r$(e),barPanes:async t=>Vre(await i9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await i9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await i9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void a9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Mq(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:WF,paneClaude:t=>Kre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+r9;for(;;){let o=await s9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${r9/1e3} s`);await a(100)}},launcherNode:e=>Rre(e,e=>n9(e,s.constants.X_OK),Lre),onPath:(e,t)=>{let n=t9(e,t,e=>n9(e,s.constants.X_OK));return n===null?null:s.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?zre(i.stdout):null;return a===null?(a9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();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=r.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(100)}return!0},typeShellLine:async(t,n)=>void await i9(e,t,t$(t.pane,`cc-candybar-lane`,[]),n)}}const Jre=/^[0-9a-f]{64}$/;function c9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Yre(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>c9(e,t).toString(`hex`),verify:(t,n)=>Jre.test(n)?ue(Buffer.from(n,`hex`),c9(e,t)):!1}}function l9(e){return E.join(e,`link.key`)}function u9(e){let t,n=()=>t??=Xre(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Xre(e){let t;try{t=s.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Zre(e),t=s.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Yre(t)}function Zre(e){s.mkdirSync(E.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;s.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{s.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{s.unlinkSync(t)}}function Qre(e,t,n){return{daemonLog:t,launcher:e=>It(e,n),storage:t=>Ire(e,t,n),doctorStores:IZ(e.state),doctorEdge:JZ,claudeInput:r$,probe:qs,laneEdge:(e,t,r,i)=>qre(e,t,r,n,i),linkSigner:u9(l9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Xr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:s.statSync}}const $re=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function d9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?$re[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const eie={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};function tie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=d9(t),o=d9(n),s={};for(let e of r){let t=eie[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function nie(e){return{ok:!0,band:e.rows.map(e=>lj(e).map(tie))}}function rie(e){return QA(nie,e)}const iie={band:e=>JSON.stringify(rie(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:m7(e)})};function f9(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)}}}function aie(e,t){t.allowHalfOpen=!1;let n=e.stats.accept();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`),a(!1);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(er(n),e=>{a(e==null),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a(!1),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3,request:n.id},null,u6)}),u=nr(r=>{let i=Zn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{if(!c){e.kind===`reply`&&e.settled(!1);return}e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.settled):d(e.sessionId,e.lane)}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(H3(t),null,u6)}).finally(()=>{c||(l(),a())})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,u6)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=f9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(tr(iie[i](e,t))),refused:e=>t.end(er(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const p9=`CC_CANDYBAR_PARENT_PID`;function oie(e){let t=e[p9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${p9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function sie(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let m9=null,h9=null,g9=null,_9=null;function v9(){if(_9===null)throw Error(`runDaemon has not started`);return _9}function y9(e,t){v9().log.log(e,t)}function cie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:an(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function lie(e){let n=N(e.host);_9={world:e,paths:n,log:new dee(n.log,e.clock)},t.on(`uncaughtException`,e=>{y9(`error`,`uncaughtException: ${e.stack||e.message}`),C9(1)}),t.on(`unhandledRejection`,e=>{y9(`error`,`unhandledRejection: ${String(e)}`),C9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{y9(`info`,`received ${e}, shutting down`),C9(0)});uie().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${x(e)}`),C9(1)}async function uie(){let{world:e,paths:n,log:r}=v9(),{host:i}=e,a=Ir(i.env);m9=await Ys(t.pid,qs(e.launcher).startTime);let o=await tc(rc(e,m9,n.registry));if(!o.decision.allow){y9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),C9(1);return}h9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),hn(n.socket);let c=Nre({...Qre(n,r,e.clock),bundle:cie(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:UF(),exit:C9});g9=c,sie({clock:e.clock,anchor:oie(i.env),probe:qs(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,de.createServer(e=>aie(c,e)),n.socket,!1)}function x9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){y9(`error`,`server error: ${a.message}`),C9(1);return}if(i){y9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}die(e,n,r).catch(b9)}),n.listen(r,()=>fie(e,r))}async function die(e,n,r){let i=await Rs(zs(gn(r)),(t,n)=>Js(t,n,qs(e.launcher)));if(i.kind===`attach-and-exit`){y9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}y9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){y9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),C9(1);return}}x9(e,n,r,!0)}function fie(e,n){let r=Hs(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}mie(n);try{s.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Fr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Fr(e.memoryLimitBytes)}MB`),ai(v9().paths.spawnBackoff),e.arm(),pie(n,r.identity)}function pie(e,n){Gs({bound:n,myPid:t.pid,readIdentity:()=>Hs(e),readLease:()=>zs(gn(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function mie(e){let n=Bs(gn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const hie=e=>(t,n,r)=>fee(e,{socket:t},`tmux-status`,n,r);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(hie(v9().world.launcher)),Vs(v9().paths.lease,t.pid),h9!==null&&nc(h9,t.pid,$s,e=>s.unlinkSync(e)),t.exit(e))}const gie={connectMs:200,budgetMs:500};async function _ie(e,t,n){return vie(t,await yie(e,t),n.includes(`--json`))}function vie(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
494
|
+
`:bie(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${fr(t)}\n`,code:1}}function yie(e,t){return ar(e,()=>({kind:`debug`,what:t}),gie,e=>`debug`in e?e.debug:void 0)}function bie(e){switch(e.what){case`vars`:return xie(e.vars);case`segments`:return Sie(e.segments);case`config`:return Cie(e.config);default:return e}}function xie(e){if(e.length===0)return`no variables (DSL not active)
|
|
495
|
+
`;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?``:` ${Tie(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${wie(a.value)}${e}${o}`)}return t.join(`
|
|
496
496
|
`)+`
|
|
497
|
-
`}function
|
|
497
|
+
`}function Sie(e){if(e.length===0)return`no segments (DSL not active)
|
|
498
498
|
`;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(`
|
|
499
499
|
`)+`
|
|
500
|
-
`}function
|
|
500
|
+
`}function Cie(e){return e===null?`config: DSL not active
|
|
501
501
|
`:JSON.stringify(e,null,2)+`
|
|
502
|
-
`}function
|
|
502
|
+
`}function wie(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Tie(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Eie(){let e=Oie();return e===null?null:s.readFileSync(e,`utf-8`)}function Die(){let e;try{e=Eie()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function Oie(){let e=E.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=E.dirname(E.resolve(n));for(;;){let t=E.join(r,e);if(s.existsSync(t))return t;let n=E.dirname(r);if(n===r)return null;r=n}}var kie=class{holds=new n7;lanes=X.observable.map(void 0,{deep:!1});answered=new Map;thrown=X.observable.box(null,{deep:!1});stop;constructor(e,t,n){this.registry=t,this.at=n,this.stop=(0,X.reaction)(()=>t.subscriptions(),t=>{let{result:n}=this.holds.declare(()=>$Y(e,this.holds,new Map(t.map(e=>[e.digest,e])),(e,t)=>t()));for(let e of this.answered.keys())n.has(e)||this.answered.delete(e);(0,X.runInAction)(()=>this.lanes.replace([...n]))},{fireImmediately:!0,onError:e=>(0,X.runInAction)(()=>this.thrown.set({error:e}))})}run(e){let t=this.lanes.get(e);if(t===void 0)return jY;let n=t.current(),r=t.fault(),i=this.answered.get(e);if(i?.from===n&&i.fact.fault===r)return i.fact;let a={reading:x8(void 0,n,this.at),fault:r};return this.answered.set(e,{from:n,fact:a}),a}async settled(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){let e=this.thrown.get();if(e!==null)throw e.error;return[...this.registry.namedRuns()].filter(([,e])=>yX(this.run(e.digest).reading)).map(([e])=>e)}close(){this.stop(),this.holds.close()}};const w9=5e3;function Aie(e,t){return{ms:t,signal:Re(e,t)}}function jie(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function T9({layers:e,config:t,compiled:n,store:r,registry:i,runs:a},o,s,c){let l=eX(o,s);return{drawn:E3(n,r,i,Fie(t,o,e.at(-1)??null,c),l,o,D9,e=>a.run(e)),opts:l}}const E9=`/home/tester`,D9=nq(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),Mie={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function Nie(e){let t=Math.floor(e);return{hook_event_name:`Status`,session_id:D9,version:`1.15.0`,cwd:`${E9}/code/cc-candybar/src`,transcript_path:`${E9}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${E9}/code/cc-candybar/src`,project_dir:`${E9}/code/cc-candybar`,added_dirs:[]},cost:{total_cost_usd:.39,total_duration_ms:93e4,total_api_duration_ms:4200,total_lines_added:512,total_lines_removed:88},context_window:{total_input_tokens:241400,total_output_tokens:0,context_window_size:1e6,used_percentage:76,remaining_percentage:24,current_usage:{input_tokens:48487,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}},rate_limits:{five_hour:{used_percentage:63,resets_at:t+2*3600},seven_day:{used_percentage:21,resets_at:t+5*86400}}}}function Pie(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]);return{lanes:{git:F({branch:`main`,status:`dirty`,aheadBehind:F({ahead:2,behind:1}),head:F(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:F(`abc1234`),operation:F(`rebase`),committedAt:F(n-780),stashCount:F(1),upstream:F(`origin/main`),repoName:F(`cc-candybar`),repoUrl:F(`https://github.com/promptctl/cc-candybar`),pullRequest:I}),usage:F({calculatedCost:.39,tokens:241400,tokenBreakdown:null}),context:F(48487),metrics:F({lastResponseTime:8.2,messageCount:8,nonPrompts:0}),activity:I,tmuxSession:F(`work`),hostName:F(`tester-box`),hostUser:F(`tester`),cache:F(n+900),speed:I,autoCompact:F(4e5),sources:new Map(r.map(e=>[e,I])),runs:new Map},today:F({sums:BJ(t,12.5,34e5),own:{}}),faults:[]}}function Fie(e,t,n,r){let i=Nie(r),a=a7(void 0,D9,Pie(e,r),{...I,at:r},r),{term:o,...s}=CX(a,{hookData:i,hints:Mie,home:E9},{sources:Object.keys(a.sources),effective:t,configFacts:{unsaved:1,resettable:Rx(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${E9}/.config/cc-candybar/config.json5`},history:{undo:1,redo:1,sinceEdit:1},back:1});return{...s,today:kX(a.builtins.today,r)}}function Iie(e,t){let n=bB(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function Lie(e,n,r,i=t.cwd(),a=w9){let o=[],c=mA(i,r,e.host.home)??null,l=En(e.host),u=hB(l,tV(ln(e.host)).read(),i,i,c??void 0);o.push(...lB(u.repos));let d=c===null?Iie(u,o):[mB(c)];if(c!==null){let e;try{e=s.statSync(c,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:c,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:c,message:`not a file`}}let f=SB(l,i,i);f!==null&&o.push(f);try{return{kind:`clean`,layers:d,warnings:o,rendered:await Bie(e,n,d,{repo:u.repos.plugins},i,o,a)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&d.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof fb&&o.push(...e.warnings),{kind:`fatal`,layers:d,message:e instanceof fb||e instanceof Error?e.message:String(e),warnings:o})}}async function Rie(e,t,n,r,i,a,o=w9){let s=t.map(e=>e.path),c=DW(En(e.host),t,$W,{warned:e=>i.push(...e)},{...n,cwd:r});PW(c.dropped);let{config:l}=c,u=new R1(e.clock),d=new QY({launcher:e.launcher,clock:e.clock}),f=new r0(u,l.globals.default_empty_value??``,new $K,null,e.host.env),p=new kie(d,f,a),m=()=>{f.dispose(),p.close(),d.close()};try{let t=u3(l,f,{cwd:r,signer:u9(l9(ln(e.host)))});i.push(...t.loadWarnings);let n=cG(l,()=>null,()=>!1),d=Aie(e.clock,o);return T9({layers:s,config:l,compiled:t,store:u,registry:f,runs:p},n,200,a),await p.settled(d.signal),{settle:d,layers:s,droppedPlugins:[...c.installed.dropped,...c.layers.flatMap(e=>e.plugins.dropped)],config:l,compiled:t,store:u,registry:f,runs:p,[Symbol.dispose]:m}}catch(e){throw m(),e}}async function zie(e,t,n,r){let i=new Map,a=new Set,o=e=>{switch(e.kind){case`rule`:i.set(`${e.slot} rule`,e.message);return;case`when`:i.set(e.where,e.error);return;case`refresh`:i.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;default:}},{config:s,compiled:c,store:l,registry:u,runs:d,settle:f}=e,{drawn:p,opts:m}=T9(e,t,n,r);for(let e of jie(f,await d.settled(f.signal)))a.add(e);let{frame:h}=D3(s,c,l,u,p,r,m,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:h,failures:i,advisories:a}}async function Bie(e,t,n,r,i,a,o){let s=Ve(new Date(e.clock.now())),c=await Rie(e,n,r,i,a,s,o),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=hS(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=cG(l,t=>t===`preset`?e:null,()=>t),r;try{r=await zie(c,n,200,s)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},r=await n(e,!1),i=[r,await n(e,!0)];for(let t of mS(l.presets))t!==e&&i.push(await n(t,!1),await n(t,!0));let o=t=>{let n=new Map;for(let e of i)for(let r of t(e)){let t=n.get(r)??new Map;t.set(e.preset,(t.get(e.preset)??new Set).add(e.customized)),n.set(r,t)}return[...n].map(([t,n])=>n.get(e)?.has(!1)?t:`${t} (under ${[...n].map(([t,n])=>[...t===e?[]:[`preset "${t}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};a.push(...o(e=>e.advisories));let u=o(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=r.rendered,f=c.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(`
|
|
503
503
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
504
|
-
`));return d}finally{c[Symbol.dispose]()}}function O9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function
|
|
505
|
-
`))a[e]=void 0;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${
|
|
506
|
-
`));let l=o.map(e=>{let n=E.basename(e),r=E.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
504
|
+
`));return d}finally{c[Symbol.dispose]()}}function O9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function Vie(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${yA(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${oj(e.rendered)}\n`:``),stderr:O9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:O9(e.warnings)+`✗ ${yA(e.layers.map(e=>e.path),`<default>`)}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const k9=`--render`,A9=`Usage: cc-candybar check [${k9}] [config-file]\n`;function Hie(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==k9);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${A9}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${A9}`}:{kind:`run`,target:n[0],render:t.includes(k9)}}async function j9(e,n){let r=Hie(e),i=t.cwd();return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:Vie(await Lie(n,UF(),vA(r.target,n.host,i).path,i),r.render)}const Uie=/^[a-z][a-z0-9+.-]*:\/\//i,Wie=/^[^@\s/]+@[^:\s/]+:/,Gie=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function Kie(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function qie(e,t,n,r){let i=pA(t,e,n);if(r(i))return{kind:`path`,dir:i};if(Uie.test(e)||Wie.test(e))return{kind:`git`,url:e,shown:Kie(e)};let a=Gie.exec(e);if(a){let e=`https://github.com/${a[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 Jie(e,t){let n=E.join(e,zz),r=Vz(n);if(`error`in r)throw Error(`${t}: could not list ${zz}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${zz}/<name>/${nz}`);return r.folders.map(e=>E.join(n,e,nz))}function Yie(e,t,n,r){let i=(r,...i)=>{let a=e.launchSync({bin:`git`,args:i,envOverlay:r,category:`plugin.git`});if(!a.ok)throw Error(`git ${i.map(e=>e===t?n:e).join(` `)} failed (${Ze(a)})`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
|
|
505
|
+
`))a[e]=void 0;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${zz}/`)}function Xie({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=s.mkdtempSync(E.join(e.tmp,`cc-candybar-plugin-`));try{return Yie(t,n.url,n.shown,E.join(i,`repo`)),r(E.join(i,`repo`))}finally{s.rmSync(i,{recursive:!0,force:!0})}}}}function Zie(e){let t;try{t=s.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 Qie(e,t,n,r){switch(r){case`updated`:s.renameSync(E.join(e,nz),E.join(t,nz));return;case`replaced`:s.renameSync(t,n),s.renameSync(e,t);return;case`installed`:s.renameSync(e,t);return}}function $ie(e,t,n,r){let i=Jie(e,n);s.mkdirSync(t,{recursive:!0});let a=s.mkdtempSync(E.join(t,`.install-`));try{let o=i.map(e=>{let t=E.join(a,E.basename(E.dirname(e)));s.mkdirSync(t);try{s.copyFileSync(e,E.join(t,nz))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),c=TW(o.map(e=>iz(E.join(e,nz),`plugins`)),$W,{root:e,git:!1},r);if(c.length>0)throw Error(c.map(e=>`${n}: ${E.join(zz,E.relative(a,e.path))} would not load: ${e.reason.split(a).join(E.join(n,zz))}`).join(`
|
|
506
|
+
`));let l=o.map(e=>{let n=E.basename(e),r=E.join(t,n);return{folder:e,name:n,target:r,placed:Zie(r)}}),u=[];try{for(let{folder:e,name:t,target:n,placed:r}of l)Qie(e,n,E.join(a,`.replaced-${t}`),r),u.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${u.join(`, `)||`none`})`)}return l.map(({target:e,placed:t})=>({path:E.join(e,nz),placed:t}))}finally{s.rmSync(a,{recursive:!0,force:!0})}}function eae(e,t){let[n,r,...i]=e;if(n!==`install`||r===void 0||i.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let a=qie(r,process.cwd(),t.host.home,e=>oV(e)!==null);if(`error`in a)return console.error(`plugin install: ${a.error}`),2;try{let e=a.kind===`path`?a.dir:a.shown,n=Xie(t,a,n=>$ie(n,Rz(En(t.host)),e,t.host.home));for(let{path:t,placed:r}of n)console.log(`${r} plugin ${E.basename(E.dirname(t))} → ${t} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function M9(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
507
507
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
508
|
-
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:qA(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function N9(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
|
|
509
|
-
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:
|
|
510
|
-
`)||null),warning:i.warning,unused:a.unused,config:a.config}}function
|
|
511
|
-
`;function
|
|
512
|
-
`);return{bytes:`\x1B[?2026h`+t.map((e,t)=>`\x1b[${t+1}H${e}[0m[K`).join(``)+`\x1B[J\x1B[?2026l`,rows:t.length}}const U9=5e3,W9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function
|
|
513
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
508
|
+
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:qA(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function N9(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 tae=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function P9(e,t,n){let{env:r}=e;return{termCols:N9(r.COLUMNS,n.columns),termRows:N9(r.LINES,n.rows),ssh:tae.some(e=>(r[e]??``)!==``),tmux:Ec(r),configEnv:gA(e,t),claudeConfigDir:Yo(r,t),terminalEnv:Pn(r)}}function F9(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function nae(e){let t=bQ(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=F9(e);if(!n.every(e=>typeof e.ago==`number`))return{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age: ${JSON.stringify(e.clients)}`};let r=[];for(let t of n){let n=eq(t.sessionId);if(!n.ok)return{kind:`failed`,reason:`the running daemon (${e.version}) reported a client whose session id ${n.problem}: ${JSON.stringify(e.clients)}`};r.push({client:ir(t.client)??null,sessionId:n.id,ago:t.ago})}return{kind:`ok`,value:{bundle:e.bundle,clients:r}}}const rae=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},iae=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 I9(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 aae(e){let t=bQ(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=I9(n?.postMortems,e=>Array.isArray(e)&&e.every(rae)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&iae(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 L9(e,t,n){let r=bQ(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=F9(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 R9=e=>kj.includes(e.role),oae=e=>L9(e,e=>typeof e.ago==`number`&&eq(e.sessionId).ok&&typeof e.claudeConfigDir==`string`&&jj.includes(e.rateLimits),`the rate-limit windows they carried`),sae=e=>L9(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&eq(e.sessionId).ok&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),cae=e=>L9(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&eq(e.sessionId).ok&&R9(e)&&Pj.includes(e.frame),`what they drew and from which project`),lae=e=>L9(e,e=>eq(e.sessionId).ok&&typeof e.ago==`number`&&R9(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function z9(e,t,n){let r=e.doctorStores?.[t],i=I9(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 uae(e){let t=bQ(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:z9(e,`marks`,Pq),clicked:z9(e,`clicked`,Lq),postMortemsRead:z9(e,`postMortemsRead`,jZ)}}async function dae(e){let t=await yQ(e);if(t.kind!==`ok`){let e={kind:`failed`,reason:fr(t).split(`
|
|
509
|
+
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:nae(t.value),rateLimits:oae(t.value),transcripts:sae(t.value),frames:cae(t.value),widths:lae(t.value),serving:aae(t.value),stores:uae(t.value)}}const fae=` (fix: click the settings menu (${vi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,pae=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${vi} by default) › 🧰 tools › 🩺 doctor`;function mae({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:fae}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${pae}\n`)}function hae({host:e,clock:t},n){let r={clock:t,locations:En(e),env:e.env,sessionState:new $K,storage:hne,signer:u9(l9(ln(e))),gates:UF(),stateDir:ln(e)},i=$5(n.projectDir,n.cwd,n.target.path,r),a=i.state??e7(n.cwd,i.repos.plugins,r);return a.registry.dispose(),{layers:i.layers,error:i.error??(a.dropped.map(e=>e.message).join(`
|
|
510
|
+
`)||null),warning:i.warning,unused:a.unused,config:a.config}}function gae(e,t,n){return n.kind===`failed`?n:FZ(e,n.value.bundle,Hq(t,n.value.clients).map(({client:e})=>e))}function _ae(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:Hq(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function vae(e,t){return t.kind===`failed`?t:{kind:`ok`,value:Hq(e,t.value).map(e=>e.transcript)}}function yae(e,t){return t.kind===`failed`?t:{kind:`ok`,value:Wq(e,t.value)}}function bae(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:uQ(e.sessionId,Hq(e,t.value))}async function xae(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=P9({env:r,home:e.home},i,a()),u=Vq(r.CLAUDE_CODE_SESSION_ID);s={...await dQ(e,l,{projectDir:Uq(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:vA(o,{env:r,home:e.home},i)},()=>null,c.serving,_ae(u,c.rateLimits,Xo(l.claudeConfigDir,e.home)),vae(u,c.transcripts),u,yae(u,c.frames),bae(u,c.widths,l.termCols??null),c.stores),urlHandler:await IQ(t),install:gae(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=$M(s);return{stdout:c.map(mae).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function Sae(){if(t.stderr.isTTY)return t.stderr;let e;try{e=m(`/dev/tty`,`r+`)}catch{return{}}let n=new ve(e),{columns:r}=n;return n.destroy(),{columns:r}}const B9=`Usage: cc-candybar doctor [config-file]
|
|
511
|
+
`;function Cae(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`));return t.length>0?{kind:`usage`,message:`doctor: unknown option ${t.join(` `)}\n${B9}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${B9}`}:{kind:`run`,configFile:n[0]}}async function wae(e,n){let r=Cae(e);return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:await xae(JZ(n.launcher,e=>hae(n,e),n.host),VQ(n.launcher,n),()=>dae(n),n.host.env,t.cwd(),Sae,r.configFile)}function Tae(e){return!e.ok&&e.code!==`RENDER_FAILED`}function Eae(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=de.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(er(c))),s.on(`data`,nr(e=>{let t=e;Tae(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 V9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function Dae(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 H9(e,t,n,r,i){let a=null,o=null,s=!1,c=250,l=(t,n)=>{o=e.clock.after(t,()=>{o=null,((n?i.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{s||u()})})},u=()=>{a=Eae(t,n,r,e=>{c=V9(c,e.ok?`frame-ok`:`frame-failed`),i.frame(e)},t=>{if(t.kind===`closed-here`||s)return;let n=Dae(t);switch(n.kind){case`exit`:i.exit(n.reason);return;case`off`:i.off(n.resp),l(5e3,!1);return;case`reconnect`:{i.fault(n.reason,c),n.kick&&Zr(e);let t=c;c=V9(c,`fault`),l(t,!0);return}}})};return u(),{close:()=>{s=!0,o?.(),a?.close()}}}function Oae(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function kae(e,n,r){let{values:i,tokens:a}=S({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),o=[e[1],...a.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],s=t.cwd(),c=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},l=Xb(i.lane);l===null&&(c(`--lane needs one of ${Ub.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let u=f9(t.stdout),d=null,f=null,p=null,m={kind:`none`},h=(e,t)=>{Oae(m,e)&&t(),m=e},g=async e=>{let i=await yr(r,e,o,s,{...P9(r.host,s,t.stderr),client:In(`frames`,n)});i.kind!==`ok`&&(c(fr(i)),M9(i).kick&&Zr(r))},_=e=>{p?.close(),p=H9(r,fn(r.host),e,l,{frame:e=>h({kind:`frame`},()=>u(`${JSON.stringify(e)}\n`)),off:e=>h({kind:`off`},()=>u(`${JSON.stringify(e)}\n`)),fault:(e,t)=>h({kind:`fault`,reason:e},()=>c(`${e}; reconnecting in ${t}ms`)),exit:e=>{c(e),t.exit(1)},beforeReconnect:()=>f===null?Promise.resolve():g(f)})};for await(let e of ye({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){c(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){c(`stdin line carries no session_id`);continue}f=t,await g(t),t.session_id!==d&&(d=t.session_id,_(d))}t.exit(0)}function Aae(e){let t=e.replace(/\n+$/,``).split(`
|
|
512
|
+
`);return{bytes:`\x1B[?2026h`+t.map((e,t)=>`\x1b[${t+1}H${e}[0m[K`).join(``)+`\x1B[J\x1B[?2026l`,rows:t.length}}const U9=5e3,W9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function jae(e,t,n,r){let i=e.split(`
|
|
513
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?f7(e,d7(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function G9(e,t,n){let[r,i]=await Promise.all([pc(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,l7]),pc(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,u7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:jae(r.stdout,i.stdout,n,t.pane)}:i:r}function K9(e){let t=e.monotonic();return n=>{if(n.kind===`ok`)t=e.monotonic();else if(e.monotonic()-t>U9)throw Error(`tmux has not answered for ${U9/1e3} s: ${n.reason}`)}}function Mae(e){let{positionals:t}=(()=>{try{return S({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${W9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(W9);return{pane:n}}async function Nae(e,n){try{return await Pae(e,n),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function Pae(e,n){let{pane:r}=Mae(e),i=Ec(n.host.env);if(i===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 a=await G9(n,i,r);if(a.kind!==`ok`)throw Error(a.reason);let o=a.placement;if(o.kind===`gone`)throw Error(`no pane ${r} on this tmux server (${i.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 s=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},c=null,l=`waiting for pane ${r}'s bar`,u=()=>c?.said.latest??l,d=``,f=K9(n.clock),p=async()=>{if(o.kind!==`shown`)return;let e=Aae(u());e.rows!==t.stdout.rows&&!o.zoomed&&f(await pc(n.launcher,i,`bar-pane.tmux`,[`resize-pane`,`-t`,i.pane,`-y`,String(e.rows)])),e.bytes!==d&&t.stdout.write(e.bytes),d=e.bytes},m=null,h=!1,g=()=>{h=!0,m??=(async()=>{try{for(;h;)h=!1,await p()}finally{m=null}})(),m.catch(s)};t.stdout.on(`resize`,()=>{d=``,g()});let _=e=>{if(c?.sessionId===e)return;if(c?.follower.close(),e===null){c=null;return}let t={latest:null},r=e=>{t.latest=e,g()};c={sessionId:e,said:t,follower:H9(n,fn(n.host),e,`pane`,{frame:e=>r(M9(vr(e)).output),off:e=>r(e.error),fault:r,exit:e=>s(Error(e))})}},v=K9(n.clock);for(;o.kind!==`gone`;){if(o.kind===`hidden`)_(null);else{let e=await br(n,i.socket,r);e.kind===`ok`?(_(e.value),l=e.value===null?`waiting for pane ${r}'s statusline to render on ${fn(n.host)}`:`waiting for pane ${r}'s bar`):(e.kind===`transient`&&(Zr(n),d=``),l=fr(e))}g(),await Le(n.clock,500);let e=await G9(n,i,r);v(e),e.kind===`ok`&&(o=e.placement)}_(null),t.stderr.write(`cc-candybar bar-pane: pane ${r} closed\n`)}const Fae=(e,t)=>new Promise((n,r)=>{let i=t=>{t?t.code===`EPIPE`?n():r(t):(e.off(`error`,i),n())};e.once(`error`,i),e.write(t,i)});async function q9(e){let n=Me(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),r=[];for(let[i,a]of[[t.stdout,e.stdout],[t.stderr,e.stderr+n]])await Fae(i,a).catch(e=>r.push(e));if(r.length>0)throw r[0];t.exit(e.code)}const J9=i(import.meta.url),Y9=Rt(),{host:X9}=Y9;je(!!X9.env.CC_CANDYBAR_DEBUG);const Z9=e=>e.some(e=>t.argv.includes(e));function Q9(){console.log(uA);let e=Cs(J9,X9),t=s.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${Hb.statusline.label} yourself (a Bun-compiled Claude Code):\n ${qt(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const $9={install:async e=>{await Is(e,J9,Y9),t.exit(0)},"install-url-handler":async()=>{cee(J9,Y9),t.exit(0)},"url-handle":async e=>{await lee(e[0],Y9)},daemon:async()=>{lie(Y9)},"daemon-stats":async e=>{await q9(await _Q(Y9,e))},frames:async()=>{await kae(t.argv,J9,Y9)},check:async e=>{await q9(await j9(e,Y9))},lint:async e=>{await q9(await j9(e,Y9))},plugin:async e=>{t.exit(eae(e,Y9))},schema:async()=>{await q9(Die())},doctor:async e=>{await q9(await wae(e,Y9))},"bar-pane":async e=>{t.exit(await Nae(e,Y9))},...Object.fromEntries(I6.map(e=>[e,async t=>{await q9(await _ie(Y9,e,t))}]))};async function Iae(){let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(n!==null&&!Object.hasOwn($9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),Z9(aA.help)&&(Q9(),t.exit(0)),Z9(aA.version)&&(console.log(`cc-candybar ${tn}`),t.exit(0)),n!==null){await $9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
514
514
|
|
|
515
515
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
516
516
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -526,4 +526,4 @@ Add to ~/.claude/settings.json:
|
|
|
526
526
|
Run with --help for more options.
|
|
527
527
|
|
|
528
528
|
To test output manually:
|
|
529
|
-
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)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=M9(await yr(Y9,e,t.argv.slice(1),t.cwd(),{...P9(X9,t.cwd(),t.stderr),client:In(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Zr(Y9),await q9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await q9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}
|
|
529
|
+
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)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=M9(await yr(Y9,e,t.argv.slice(1),t.cwd(),{...P9(X9,t.cwd(),t.stderr),client:In(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Zr(Y9),await q9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await q9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}Iae();export{};
|