@promptctl/cc-candybar 1.193.0 → 1.194.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +81 -81
- package/package.json +5 -5
- package/schema/cc-candybar.schema.json +0 -57
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 ee,setImmediate as w}from"node:timers";import{spawn as te,spawnSync as ne}from"node:child_process";import T,{basename as re,dirname as E,isAbsolute as D,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 e+t}function Ie(e,t){return Math.round(t-e)}function A(e,t){return Ie(t,e.monotonic())}const Le={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=w(e);return()=>ee(t)}};function Re(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 ze(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 Be(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function Ve(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const He=e=>e.getTime()/1e3,Ue=e=>new Date(e*1e3),We=e=>He(new Date(e.now()));function Ge(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 Ke={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function qe(e,t,n){let r=Ke[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 Je(e,t){return{...e.inherited,...t.envOverlay}}function Ye(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 Xe=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function Ze(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 Xe(n);let i=Math.max(n.lastIndexOf(`
|
|
3
3
|
`),n.lastIndexOf(`\r`))+1;return`${Xe(n.slice(0,r).trim())} … ${Xe(n.slice(i).trim())}`}function Qe(e,t=``){let n=Ze(e,e.stderr);return`${Ye(e)}${t}${n===``?``:`: ${n}`}`}const $e=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function et(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 tt(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function nt(e,t,n){let r=rt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function rt(e,t,n){if(e.scope.signal.aborted)return $e(e.scope.signal);if(n?.aborted)return $e(n);let r=qe(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:et(t,r.minIntervalMs,r.sinceLastMs)}const it=`\$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 at(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function ot(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),at(e,n))}const st=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,ct=e=>e===`cut`?`output cut at the ${_t}-byte bound, so the program holding it now fails its writes`:`output failed to read`,lt=`a launched program's pipe outlived its launch: `;function ut(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:`${lt}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${ct(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${lt}${n} ${ct(t)}`})}function dt(e,t){let n=e.pipeEvent;n===null||!Ve(n,t)||(e.pipeEvent={...n,answered:!0})}function ft(e,t,n){let r=e.pipeEvent,i=r===null?`over`:Be(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:st(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function pt(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[it],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,A(n,r)),at(e,`did not start: ${Ge(i,void 0)}`),null}t?.onEnd(`lifeline`,A(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>at(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&at(e,null)}),i.once(`error`,t=>ot(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>ot(e,i,`exited ${n??t}`)),a.on(`error`,t=>ot(e,i,`pipe failed: ${t.message}`)),tt(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 mt(e,t){e.liveGroups.add(t),e.lifeline??=pt(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function ht(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function gt(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const _t=16*1024*1024,vt=`output exceeded ${_t} bytes`,yt=e=>`timed out after ${e/1e3} s`;function bt(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?ut(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(),ut(e,`cut`,t);return}let d=Math.max(0,_t-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||xt(e,t,n,()=>u)}}}function xt(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 St=()=>`closed`;function Ct(e,t){e.on(`error`,()=>{}),e.end(t)}async function wt(e,t){let{stats:n,clock:r}=e.scope,i=nt(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:Je(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:Ge(e,t.cwd)});return}let c=s.pid;c!==void 0&&mt(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ne(`output-limit`),failed:e=>{d??=e.message,ne(`pipe-error`)}},p=bt(e,t.category,s.stdout,f),m=bt(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>ne(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&ht(e,c),n?.onEnd(t.category,A(r,a)),s.off(`close`,re),s.off(`error`,T),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&xt(e,t.category,u,St),i())},ee=e=>C(()=>i(e)),w=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),ee({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},te=()=>re(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(te);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ne=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(te);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{w(t,`SIGKILL`),l.then(()=>r.defer(te))}),w(t,`SIGTERM`))},T=e=>{ee({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:Ge(e,t.cwd)})};s.on(`error`,T);let re=(e,n)=>{if(b!==null){ee({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:yt(t.timeoutMs??0)}:b===`output-limit`?{error:vt}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){ee({ok:!0,...h(),exitCode:e});return}ee({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,re),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ne(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&Ct(u,t.stdinInput)})}function Tt(e,t){let{stats:n,clock:r}=e.scope,i=nt(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:Je(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`?yt(t.timeoutMs??0):Ge(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:Ge(e,t.cwd)}}}function Et(e,t){let{stats:n,clock:r}=e.scope,i=nt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=Dt(e,t);return n?.onEnd(t.category,A(r,a)),o}function Dt(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:Je(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Ge(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 Ot=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function kt(e,t,n){let{stats:r,clock:i}=e.scope,a=nt(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:Je(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:Ge(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 At(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 jt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Ot(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 Mt(e,t,n){return Pt(e,t,n).launcher}function Nt(e,t,n){let{launcher:r,state:i}=Pt(e,t,n);return{...r,launchSync:e=>Tt(i,e)}}function Pt(e,t,n){let r={clock:t,launch:e=>tt(i,wt(i,e)),launchDetachedSync:e=>Et(i,e),launchJobSync:(e,t)=>kt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>jt(n,t,e,r,i),launcherWarnings:(e,t)=>ft(i,e,t),answeredPipeEvent:e=>dt(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&&ot(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:st(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>He(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()),gt(i)},{once:!0}),{launcher:r,state:i}}function Ft(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const It={spawn:(e,t,n)=>te(e,t,n),spawnSync:(e,t,n)=>ne(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Ft(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}}},Lt=(e,t)=>Mt(e,t,It),Rt=(e,t)=>Nt(e,t,It);function zt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Le;return{host:e,launcher:Rt({inherited:process.env},t),clock:t}}const Bt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Vt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ht(e){return Bt.test(e)?e:Vt(e)}function Ut(e){return`${e.dir===void 0?``:`cd ${Ht(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Ht(t)} `).join(``)}${[e.program,...e.args].map(Ht).join(` `)}`}const j=`cc-extra`;function Wt(e){return T.join(T.dirname(e),j,`src`,`bun-attach.js`)}function Gt(e){return T.join(T.dirname(e),`bun-graph.js`)}const Kt=`attach-preload.cjs`;function qt(e){return T.join(T.dirname(e),Kt)}function Jt(e,t){return Ut({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Yt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function M(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function Xt(e,t,n=Yt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=T.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Xt(e,r):[[T.relative(e,r).split(T.sep).join(`/`),M(r,i)]]})}function Zt(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 Qt(e){return Zt(Xt(e,e))}const $t=[`Cargo.toml`,`Cargo.lock`,`src`];function en(e){return Zt(Xt(e,e,e=>$t.includes(e)))}const tn=e=>e.slice(0,7),nn=`1.
|
|
4
|
+
`),withdraw:()=>l.end()})}function At(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 jt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{y(a,`${Ot(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 Mt(e,t,n){return Pt(e,t,n).launcher}function Nt(e,t,n){let{launcher:r,state:i}=Pt(e,t,n);return{...r,launchSync:e=>Tt(i,e)}}function Pt(e,t,n){let r={clock:t,launch:e=>tt(i,wt(i,e)),launchDetachedSync:e=>Et(i,e),launchJobSync:(e,t)=>kt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>jt(n,t,e,r,i),launcherWarnings:(e,t)=>ft(i,e,t),answeredPipeEvent:e=>dt(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&&ot(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:st(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>He(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()),gt(i)},{once:!0}),{launcher:r,state:i}}function Ft(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const It={spawn:(e,t,n)=>te(e,t,n),spawnSync:(e,t,n)=>ne(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Ft(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}}},Lt=(e,t)=>Mt(e,t,It),Rt=(e,t)=>Nt(e,t,It);function zt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=Le;return{host:e,launcher:Rt({inherited:process.env},t),clock:t}}const Bt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Vt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ht(e){return Bt.test(e)?e:Vt(e)}function Ut(e){return`${e.dir===void 0?``:`cd ${Ht(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Ht(t)} `).join(``)}${[e.program,...e.args].map(Ht).join(` `)}`}const j=`cc-extra`;function Wt(e){return T.join(T.dirname(e),j,`src`,`bun-attach.js`)}function Gt(e){return T.join(T.dirname(e),`bun-graph.js`)}const Kt=`attach-preload.cjs`;function qt(e){return T.join(T.dirname(e),Kt)}function Jt(e,t){return Ut({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Yt=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function M(e,t){return t.isSymbolicLink()?Buffer.from(s.readlinkSync(e)):s.readFileSync(e)}function Xt(e,t,n=Yt){return s.readdirSync(t).filter(n).sort().flatMap(n=>{let r=T.join(t,n),i=s.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Xt(e,r):[[T.relative(e,r).split(T.sep).join(`/`),M(r,i)]]})}function Zt(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 Qt(e){return Zt(Xt(e,e))}const $t=[`Cargo.toml`,`Cargo.lock`,`src`];function en(e){return Zt(Xt(e,e,e=>$t.includes(e)))}const tn=e=>e.slice(0,7),nn=`1.194.0`;function rn(e){let t=T.dirname(T.dirname(e));return s.existsSync(T.join(t,`src`))?t:null}function an(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:nn,digest:e}}function on(){return`d49b8ed4c96f8212b84ab113c4bfec099cc3c9d9d0b80b2904c9d99e0d413f6a`}function sn(e){let t=JSON.parse(s.readFileSync(T.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${T.join(e,`package.json`)} has no version string`);return n}function cn(e,t){try{let n=rn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Qt(T.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:sn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function ln(e,t){let n=e[t];return n&&n.length>0?n:void 0}function un(e){let t=ln(e.env,`XDG_STATE_HOME`)??T.join(e.home,`.local`,`state`);return T.join(t,`cc-candybar`)}function dn(e){let t=ln(e.env,`XDG_CACHE_HOME`)??T.join(e.home,`.cache`);return T.join(t,`cc-candybar`)}function fn(e){return un(e)}function pn(e){return e.env.CC_CANDYBAR_SOCKET||mn()}function mn(){let e=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function hn(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 gn(e){hn(T.dirname(e));for(let t of[e,_n(e)])try{if(s.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function _n(e){return`${e}.lease`}function vn(e){return _n(pn(e))}function yn(e){return T.join(un(e),`session-state.json`)}function bn(e){return T.join(un(e),`settings-history.json`)}function xn(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return T.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function Sn(e){return T.join(un(e),`spawn.lock`)}function Cn(e){return T.join(un(e),`spawn.cooldown`)}function wn(e){return T.join(un(e),`spawn.backoff`)}function Tn(e){return T.join(un(e),`watch-probe`)}function N(e){return T.join(un(e),`daemon.log`)}function En(e){return{socket:pn(e),lease:vn(e),state:un(e),registry:xn(e),log:N(e),sessionState:yn(e),settingsHistory:bn(e),watchProbe:Tn(e),spawnBackoff:wn(e)}}function Dn(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${T.join(ln(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:ln(t,`XDG_CONFIG_HOME`)??T.join(e.home,`.config`),dataHome:ln(t,`XDG_DATA_HOME`)??T.join(e.home,`.local`,`share`),dataDirs:(ln(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function On(e,t,n){let r=kn(e);s.mkdirSync(T.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 kn(e){return An(e).at(-1)}function An(e){let{hops:t,stopped:n}=jn(e);if(n!==null)throw n;return t}function jn(e){let t=[e];try{for(let e=0;e<Nn;e++){let e=Mn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${Nn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function Mn(e){try{return s.lstatSync(e).isSymbolicLink()?T.resolve(s.realpathSync(T.dirname(e)),s.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Nn=40,Pn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Fn(e){return Object.fromEntries(Pn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const In=[`native`,`node`,`frames`];function Ln(e,t){return{kind:e,bundle:t,source:null}}const Rn=[`ansi`,`frame`],zn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Bn(e){let t=Yn(e.termCols),n=Yn(e.termRows),r=Xn(e.ssh),i=qn(e.tmux),a=Kn(e.configEnv),o=Kn(e.claudeConfigDir),s=Gn(e.terminalEnv),c=ar(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 Vn(e,t){return zn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Hn(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 Un={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Wn(e){let t=Object.keys(Un).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Un[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
5
5
|
`)}function Gn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Pn.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 Kn(e){return typeof e==`string`&&T.isAbsolute(e)?e:void 0}function qn(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 Jn=1e4;function Yn(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Jn?Jn:t}function Xn(e){return typeof e==`boolean`?e:void 0}const Zn=new Set([...[],1]);function Qn(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}var $n=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},er=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function tr(e){return nr(JSON.stringify(e))}function nr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function rr(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 $n(`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 $n(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function ir(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 er(`deadline`))})}),l=rr(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(tr(t))})}function ar(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Kn(n);return In.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function or(e,t,n,r){let i;try{i=await fr(pn(e.host),n.connectMs,e.clock)}catch(e){return dr(e)}return sr(i,e.clock,t,n,r)}async function sr(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await ir(e,{v:3,...o},a,t);return ur(o.kind,s,i)}catch(e){return dr(e)}finally{e.destroy()}}function cr(e,t){return typeof e==`string`?e:t}function lr(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ur(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=cr(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:lr(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 dr(e){if(e instanceof $n||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 er?{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 fr(e,t,n){return new Promise((r,i)=>{let a=de.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new er(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function pr(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 mr(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 hr(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 gr={connectMs:50,budgetMs:150},_r={connectMs:50,budgetMs:350};function vr(e){let t=e.output;return typeof t==`string`?t:void 0}function yr(e){return ur(`render`,e,vr)}function br(e,t,n,r,i,a=gr){return or(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,vr)}function xr(e,t,n){return or(e,()=>({kind:`pane-session`,socket:t,pane:n}),_r,e=>`paneSession`in e?e.paneSession:void 0)}function Sr(e,t,n){return or(e,()=>({kind:`click`,verb:t,value:n}),_r,vr)}const Cr=5e3;async function wr(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 Tr=`/usr/bin/footprint`;function Er(e,t,n){return t===`darwin`?[Ar(e,Tr,[`-p`,String(n)]),Ar(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[jr(`/proc/self/smaps_rollup`),jr(`/proc/self/status`)]:[]}function Dr(e,t,n){return t===`darwin`?Or(n,t=>e.launch({bin:Tr,args:t,timeoutMs:Cr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Or(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 ${Qe(r)}`};let i=kr(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 kr(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Ar(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:Cr,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:Qe(r)}}}}function jr(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 Mr=`CC_CANDYBAR_RSS_LIMIT_MB`;function Nr(e){let t=e[Mr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Mr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Pr(e){return Nr(e)*2}const Fr=1024*1024,Ir=e=>Math.round(e/Fr);function Lr(e){return Nr(e)*Fr}const Rr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function zr(e,t){return e>t}function Br(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 Vr=.75;function Hr(e,t){return e>t*Vr}function Ur(e,t,n){let{prefix:r,suffix:i}=Rr[t];return T.join(e,`${r}${n}${i}`)}function Wr(e){for(let t of Object.keys(Rr)){let{prefix:n,suffix:r}=Rr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Gr(e){let t=e.limitBytes??1024*Fr,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=Br(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Jr(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Kr(c)} > limit ${Ir(t)} MB (rss ${Ir(a)} MB, v8 heap ${Ir(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Yr(e.log,`memory report`,async()=>{let t=Ur(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 Yr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Ur(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Yr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Xr(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Yr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Hr(i.charge.bytes,t)?`${Kr(i.charge)} approaching limit ${Ir(t)} MB (v8 heap ${Ir(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Xr(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 Kr(e){return e.kind===`charged`?`${e.measure} ${Ir(e.bytes)} MB`:`rss ${Ir(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Ir(e.gap)} MB gap`} (standing in: ${e.unread})`}function qr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Jr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Ir(e.gap)}MB`:``;return`measure=${qr(e)} charge=${Ir(e.bytes)}MB rss=${Ir(t)}MB heap=${Ir(n)}MB limit=${Ir(r)}MB${i}`}async function Yr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Xr(e){let t=new Map;for(let n of e){let e=T.basename(n),r=Wr(e);if(r===null)continue;let{prefix:i,suffix:a}=Rr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Rr);return[...t].sort(([e],[t])=>zr(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function Zr(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:Dr(n.launcher,process.platform,process.pid),captureMemoryReport:()=>wr(Er(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=>Wr(e)!==null).map(e=>T.join(i,e))},removeFile:e=>s.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Qr(e,n={}){let{host:r,clock:i}=e;if(mi(r)!==null)return;let a=n.spawn??(()=>gi(e)),o=di(r,i);if(o.kind===`contended`){let e=ei(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),$r(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),$r(r,i,a);return}try{$r(r,i,a)}finally{pi()}}function $r(e,t,n){si(e,t)&&ti(n)}function ei(e,t){try{let n=s.statSync(Sn(e));return t.now()-n.mtimeMs}catch{return null}}function ti(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 ni(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function ri(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function ii(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 ai(e,n){try{s.mkdirSync(T.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 oi(e){try{s.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function si(e,n){let r=Cn(e),i=wn(e),a=ii(i),o=ni(ci(r,n),ri(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`),li(r,n),ai(i,Math.min(a+1,5)),!0)}function ci(e,t){try{return t.now()-s.statSync(e).mtimeMs}catch{return null}}function li(e,n){try{s.mkdirSync(T.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 ui=null;function di(e,n){let r=Sn(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 ui={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(!fi(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 fi(e,t){try{let n=s.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function pi(){if(!ui)return;let{fd:e,path:t}=ui;ui=null;try{s.closeSync(e)}catch{}try{s.unlinkSync(t)}catch{}}function mi(e){try{return s.mkdirSync(fn(e),{recursive:!0}),null}catch(t){return`mkdir ${fn(e)}: ${t.message}`}}function hi(e,t){return[`--max-old-space-size=${Pr(t)}`,e,`daemon`]}function gi({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:hi(i,e.env),category:`daemon-spawn`}).ok:!1}const P=`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:[P,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.`,F=`candybar.`,Fi=[ji,Mi,Ni,Pi,F];function Ii(e){return Fi.some(t=>e.startsWith(t))}const Li=`${F}menu`,Ri=_i,zi={variable:Li,key:Li,member:Ri},Bi=`${F}diagnostics`,Vi=`cc-candybar`,Hi=`CCCandybarURLHandler`,Ui=`dispatch`,Wi=`set-state`,Gi=`step-state`,Ki=`copy`,qi=`open-vscode`,Ji=`toolbar-toggle`,Yi=`set-config`,Xi=`step-config`,Zi=`save`,Qi=`save-preset`,$i=`save-theme-default`,ea=`delete-preset`,ta=`reset-config`,na=`apply-layout-op`,ra=`undo`,ia=`redo`,aa=`back`,oa=`rewind`,sa=`apply-update`,ca=`doctor-run`,la=`doctor-fix`,ua=`doctor-mark`,da=`doctor-probe`,fa=`slash`,pa=`repo-config`,ma=`copy-diagnostic`,ha=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,ga=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function _a(e,t){if(e===Bi)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!Ii(e))return n;let r=ga(ga(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 va(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const ya={[Wi]:([,...e])=>e.flatMap((t,n)=>n%2==0?[_a(t,e[n+1])]:[]),[Gi]:([,e,t])=>[ha(e,t)],[Ki]:([e])=>[`copy ${va(e)}`],[qi]:([e])=>[`open ${e} in vs code`],[Ji]:()=>[`toggle the toolbar`],[Yi]:([,e,t])=>[`save ${e} as ${t}`],[Xi]:([,e,t])=>[`save ${ha(e,t)}`],[Zi]:()=>[`save settings`],[Qi]:()=>[`save as a new preset`],[$i]:()=>[`save this look for the theme`],[ea]:([,e])=>[`delete preset ${e}`],[ta]:([,...e])=>e.map(e=>`reset ${e}`),[na]:([,e,t])=>[`edit ${t} in ${e}`],[ra]:()=>[`undo`],[ia]:()=>[`redo`],[aa]:()=>[`go back`],[oa]:()=>[`cancel edits`],[sa]:()=>[`update cc-candybar`],[ca]:()=>[`run doctor`],[la]:([,e])=>[`fix ${e}`],[ua]:([,e,t])=>[`mark ${e} ${t}`],[fa]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[pa]:([,e,t])=>[`mark config in ${e} ${t}`],[ma]:()=>[`copy diagnostic`]},ba=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function xa(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=>ya[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function Sa(e){return e.map(encodeURIComponent).join(`/`)}function Ca(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function wa(e){return decodeURIComponent(e.split(`/`,1)[0])}function Ta(e,t=xa(e)){let n=e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Sa(e.args)}`)}`);return`${Vi}://${Ui}/${[`does=${ba(t)}`,...n].join(`&`)}`}function Ea(e){return new r(e).getAll(`e`).map(Aa)}const Da=new Set([Wi,ta]);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(),ne[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===`
|
|
@@ -55,26 +55,26 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
55
55
|
|
|
56
56
|
`)}},pb=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
|
|
57
57
|
`)),this.errors=e,this.name=`DroppedPlacements`}};function J(e,t){return mb(e)(t)}function mb(e){let t,n=()=>(t??={node:hb(e)},t.node);return t=>gb(e,n,t)}function hb(e){try{return Ua(e)}catch(e){if(e instanceof La)return;throw e}}function gb(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?_b(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=vb(e,i,t);if(n===-1)return a===void 0?void 0:yb(e,a);i=n,a=n}return a===void 0?void 0:yb(e,a)}function _b(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:yb(e,i.span.start)}function vb(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 yb(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function bb(e,t){try{return Ua(t),null}catch(n){if(!(n instanceof La))throw n;return`${e}:${yb(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function xb(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 Sb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Cb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function wb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function Tb(e,t,n){let r=wb(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Jv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function Eb(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 ${kb(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function Db(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ob(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function kb(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Ab(e,t,n,r){return Db(r)?(Pb(e,n,r,t.noun,new Set(Object.keys(t.fields)),jb(e,t.removed??{},n,r)),Mb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Ob(r)}`,line:J(e.source,n.split(`.`))}),null)}function jb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Fb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Mb(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 Nb=new Set;function Pb(e,t,n,r,i,a=Nb){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:J(e.source,[...t.split(`.`),o])})}function Fb(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Ib(e,t,n,r){if(!Db(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Ob(r)}`,line:J(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:J(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:J(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:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Lb(e,t,n,r){if(!Db(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Ob(r)}`,line:J(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 ${Ob(i)}`,line:J(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:J(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 Pb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Rb(e,t,n){return{json:Qb(Xb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function zb(e){return(...t)=>e()(...t)}function Bb(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:J(n.source,o.split(`.`))}),null}return a}}function Vb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>wb(e,t,r,n)}}function Hb(){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 ${Ob(i)}`,line:J(e.source,[n])});return}return i}}}}function Ub(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 ${kb(o)}`,line:J(e.source,[i])});return}return o}}}}function Wb(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 ${kb(a)}`,line:J(e.source,[r])});return}return a}}}}function Gb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Tb(e,t,r)}}function Kb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Sb(e,t,r,n)??void 0}}function qb(e,t){return D(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Jb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Sb(e,t,r,n);if(i===null)return;let a=qb(`${t}.${n}`,i);return a===null?i:Fb(e,`${t}.${n}`,a)??void 0}}}function Yb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Eb(t,n,i,r,e)}}function Xb(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 Zb(e){return Xb(e.fields)}function Qb(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function $b(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function ex(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const tx=[`claude`,`tmux`],nx=`ne .tmux.pane ""`,rx={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}},ix=Object.keys(rx),ax=ix.filter(e=>rx[e].switch.on===!0),ox={by:`request`},sx=e=>`drawing.${e}`,cx={subscribers:0,fps:0,shown:!0},lx=(e,t)=>`feeds.${e}.${t}`;function ux(e){return Object.fromEntries(ix.map(t=>[t,e(t)]))}const dx=ux(()=>cx);function fx(e){return typeof e==`string`&&Object.hasOwn(rx,e)?e:null}const px=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),mx=[...px(3,1),...px(3,.25)],hx=mx.reduce((e,{seconds:t})=>e+t,0),Vee={min:15,max:600,step:15},Hee=(e,t)=>e+t,Uee=e=>e-hx,gx=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),_x=(e,t,n={})=>({spec:Yb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),vx=e=>t=>e.includes(t)?`🧪 ${t}`:t,Wee={spec:Hb(),domain:`bool`,parse:jy},Gee=e=>({spec:Ub(e),domain:e,parse:t=>My(t,e)});function yx(e,t,n,r={}){return{kind:`session`,..._x(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function bx(e,t){return{kind:`session`,...Wee,floor:e,control:t,themeDefault:!1}}function xx(e,t,n){return{kind:`session`,...Gee(e),floor:t,control:n,themeDefault:!1}}function Sx(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const Cx=e=>({kind:`text`,spec:e}),Kee={required:!1,json:{enum:[...Sy]},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: ${Sy.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return Eb(e,t,r,n,Sy)}},qee={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=wb(e,t,r,n);return ry(i)?i:Tb(e,t,r)}},Jee={required:!1,json:{anyOf:[{enum:[...fy]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ry(i)?i:Eb(e,t,r,n,fy)}},wx=/^[^\r\n]*\S[^\r\n]*$/u,Tx=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Yee={required:!1,json:{type:`string`,pattern:wx.source,not:{pattern:Tx.source}},parse:(e,t,n,r)=>{let i=wb(e,t,r,n);if(i===void 0||wx.test(i)&&!Tx.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:J(e.source,[...t.split(`.`),n])})}},Xee=Object.fromEntries(ax.map(e=>[rx[e].switch.setting,bx(!1,gx(rx[e].label,`toggles`))])),Zee={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Qee={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Zee[e]})},Ex={palette:Sx(`theme`,qee,{themes:`themes`},gx(`🎨 theme`,`door`)),preset:Sx(`preset`,Vb(),{from:`presets`},gx(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:Sx(`style`,Vb(),{from:`styles`},gx(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:Sx(`effect`,Jee,{from:fy},gx(`✨ effect`,`look`)),endcaps:yx(yy,`powerline`,gx(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:yx(Ty,`accent`,gx(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:vx(q_),themeDefault:!0}),shade:yx(Ey,`middle`,gx(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:vx(I_),themeDefault:!0}),transitions:bx(!1,gx(`fade in/out`,`look`)),animationSpeed:yx(my,`1x`,gx(`speed`,`look`)),autoWrap:bx(!0,gx(`wrap`,`config`)),padding:xx({...Ay,step:1},1,gx(`padding`,`config`)),updateNotice:bx(!0,gx(`update notice`,`config`)),menuTimeout:xx(Vee,120,gx(`menu timeout`,`config`)),renderer:yx(tx,`claude`,gx(`renderer`,`config`,{shown:nx}),{optionDomain:`renderers`,library:Qee}),...Xee,colorCompatibility:{kind:`config`,..._x(Sy,`colorCompatibilities`),spec:Kee,floor:`truecolor`},default_empty_value:Cx(Vb()),default_separator:Cx(Vb()),menuGlyph:Cx(Yee)},Dx=Object.entries(Ex),Ox=Dx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),$ee=Dx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),kx=Dx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),ete=Dx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Ax(e){return Ex[e]}const jx=e=>Ax(e).floor;function Mx(e){let t=Ex[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const Nx=e=>`${e}.effective`,tte=e=>{let t=Ex[e];return t.kind===`selection`?t.sessionKey:e},Px=Object.fromEntries($ee.map(e=>{let t=tte(e);return[t,{configKey:e,sessionKey:t,effectiveVar:Nx(t),...Ex[e].control}]})),Fx=Object.keys(Px),Ix=Object.values(Px),Lx=Ox.filter(e=>Ex[e].kind===`config`).map(e=>({configKey:e,effectiveVar:Nx(e)})),nte=new Set(Lx.map(e=>e.configKey)),Rx=new Map([...Ix,...Lx].map(e=>[e.configKey,e.effectiveVar])),zx=new Map(Ix.map(e=>[e.sessionKey,e.effectiveVar]));function Bx(e){return Object.fromEntries(Fx.map(t=>[t,e(t)]))}const Vx=new Map(Fx.map(e=>[Px[e].sessionKey,e])),Hx=new Map;function Ux(e){let t=Gx(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 Wx(e,t){return e===`bar`?t:Ux(e)}function Gx(e){let t=Hx.get(e);if(t!==void 0)return t;let n=bee(e);return n===null?null:(Hx.set(e,n),n)}function Kx(e,t){return rte(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Bd(e,t))}const rte=S_();function qx(e){let t=Gx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Jx(e,t,n){let r=qx(e);return r===null?(n(dy(t,`palette`,`"${e}" names no installed theme${Jv(e)}`)),Yx()):r}function ite(e,t,n){return iy(e,t,n,Yx(),qx)}function Yx(){return{kind:`decided`,name:Yv,value:Ux(Yv)}}const Xx=/^[A-Za-z_][A-Za-z0-9_]*$/;function ate(e){return`#${e+1}`}const Zx={rows:{}};function Qx(e){return`rows`in e}function $x(e){return Object.fromEntries(e.map((e,t)=>[ate(t),e]))}function ote(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:$x(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:$x([n])}}function eS(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function tS(e){return Qx(e)?eS(e):e}function*nS(e,t){if(!Qx(e)){yield*Hy(e,t);return}yield[eS(e),t];for(let[n,r]of Object.entries(e.rows))yield*Hy(r,`${t}.rows.${n}`)}function rS(e,t){return Qx(e)?{...t,...e,rows:{...t.rows,...e.rows}}:ote(e)}function iS(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...zy(eS(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||Fy(e)===t.id)))return e;let i=r.find(e=>Fy(e)===n);if(i!==void 0)return aS(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,oS(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]))}}:aS(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function aS(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function oS(e,t,n,r){if(e.kind===`segment`&&Fy(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`?sS(e,t,n,r):cS(e,t,n,r)}function sS(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&Fy(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`?sS(a,t,n,r):cS(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function cS(e,t,n,r){let i=!1,a=Ry(e,e=>{let a=sS(e,t,n,r);return i=a!==null,a??e});return i?a:null}function lS(e){if(!Qx(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const uS=`default`,dS={};function fS(e){return[...new Set([uS,...Object.keys(e)])]}function pS(e,t,n){return ty(void 0,e,t,uS,n)}function mS(e,t){let n={[uS]:dS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${uS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function hS(e,t){let n=mS(e.presets,t).root??Zx;return{node:eS(rS(n,e.root)),path:lS(n)?`presets.${t}.root`:`root`}}function gS(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=iS(e.root,t),i=Object.entries(e.presets).filter(([,e])=>lS(e.root??Zx)).map(([n,r])=>({name:n,preset:r,...iS(rS(r.root??Zx,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:eS(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>_S(e,`${t} (in ${n.join(`, `)})`)))}}function _S(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function vS(e,t){return{...e.globals,...mS(e.presets,t).globals}}const yS=new Map;function bS(e,t,n={}){yS.set(e,{permanent:!0,resolve:t,...n})}bS(`themes`,()=>Zv(),{paletteOf:e=>Ux(e)});const xS=`placementThemes`;bS(xS,Qv,{paletteOf:(e,t)=>Wx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of ete)bS(e,()=>t,{library:n,labelOf:r});function SS(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Kx(n.basePalette,e.styles[t])}],[`presets`,{members:fS(e.presets)}]])}function CS(e){return[...new Set([...yS.keys(),...e.keys()])]}function wS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=yS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(ES(e,t))}const TS=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function ES(e,t){let n=TS.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${CS(t).join(`, `)})`}const DS=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function OS(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*kS(e){let t=[];AS(e,(e,n)=>(t.push([n,e]),e)),yield*t}function AS(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 jS(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const MS=[`plugins`,`repo`];function NS({scope:e,name:t}){return`${e}.${t}`}function PS(e){return t=>t===e||t.startsWith(`${e}.`)}const FS=`self`;function IS(e){return MS.find(t=>e===t||e.startsWith(`${t}.`))}function LS(e,t){let n=IS(e);if(n===void 0||n===e)return``;let r=MS.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)`}const RS=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*zS(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 BS=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,VS=RegExp(`^(?:(\\$)(?:\\.(${BS}))?|\\.(${BS})?)(?=[\\s)]|$)`);function HS(e,t,n){let r=VS.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 US=/^(\w+)\b\s*([\s\S]*)$/;function*WS(e,t){let n=[t];for(let r of zS(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=US.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:HS(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(HS(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const GS=/(?<![.$])\btemplate\s+$/;function*KS(e,t,n){let r=0;for(let i of[...e.matchAll(RS)]){let a=i.index+i[0].length;GS.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:HS(e.slice(a),t,n),index:i.index}),r=a}}function*qS(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...WS(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...KS(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 JS(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const YS=new WeakMap;function XS(e,t){let n=YS.get(t);return n===void 0&&(n=JS(e=>[...qS(e,t)]),YS.set(t,n)),n(e)}const ZS=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${BS})`,`g`);function*QS({code:e,dot:t,root:n}){let r=e.replace(RS,``);for(let e of[...r.matchAll(ZS)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function $S(e,t){let n=new Map;for(let r of XS(e,t))for(let e of QS(r))n.has(e)||n.set(e,r.via);return n}const eC=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,tC={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*nC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(RS)]){let a=e.slice(t,i.index),o=eC.exec(a);o===null?a.trim()!==``&&(n=0):(n=tC[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 rC(e,t){let n=new Map;for(let{code:r,via:i}of XS(e,t))for(let{name:e,site:t}of nC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const iC=RegExp(`^${Vi}://([a-z][a-z0-9-]*)`);function aC(e,t){let n=new Map;for(let{code:r,via:i}of XS(e,t))for(let e of r.matchAll(RS)){let t=iC.exec(e[0].slice(1,-1))?.[1];if(t===void 0)continue;let r=`${t}\0${i??`\0`}`;n.has(r)||n.set(r,{verb:t,via:i})}return[...n.values()]}const oC=e=>Object.keys(tC).filter(t=>tC[t]>=e).join(`|`),sC=RegExp(`(?<![\\w.$])(?:(?:${oC(1)})\\s+|(?:${oC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function cC(e,t){for(let{code:n}of XS(e,t))if(sC.test(n.replace(RS,`""`)))return!0;return!1}const lC=/(?<![\w.$])[A-Za-z_]\w*/g;function uC(e,t){let n=new Set;for(let{code:r}of XS(e,t))for(let[e]of r.replace(RS,``).matchAll(lC))n.add(e);return n}function dC(e,t){return new Set([...fC(e,t)].filter(e=>Object.hasOwn(t,e)))}function fC(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of XS(e,t))for(let{name:e}of KS(r,i,a))n.add(e);return n}const pC=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function mC(e,t,n){let r=pC(t),i=PS(t),a=[];for(let{dot:t,block:n}of WS(e,``)){let e=n.text.replace(RS,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[...KS(n.text,t,``),...nC(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*hC(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*gC(e){for(let[t,n]of hC(e))yield[t,n]}function _C(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 vC(e,t){return _C(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function yC(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),bC(r)&&n.add(e)};for(let[t,n]of gC(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function bC(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&Wy(e.parse)===`json`}var xC=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,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(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 ee(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 w(e,t){return{t:e,i:t,o:te,u:ne}}function te(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,re(e,0,0,n,!1,!1)),2)}function ne(e,t,n,r){let i=re(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function T(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 re(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 E(e,t){return{t:e,i:t,o:D,u:ie}}function D(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&&(A(),!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 Ie(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 A(){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(),Ie(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=E(cn),un=ge(E(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return O(ln,e,t);if(o(e))return ge(E(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),A())}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=w(`flow`),Wn=w(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return T(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,T),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),Ie(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||{})}})),SC=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=T(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 ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let w=Reflect.ownKeys;function te(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ne(e){return e===null?null:typeof e==`object`?``+e:e}function T(e,t){return o.hasOwnProperty.call(e,t)}let re=Object.getOwnPropertyDescriptors;function E(e,t){return!!(e&t)}function D(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 E(this.flags_,1)}set isBeingObserved(e){this.flags_=D(this.flags_,1,e)}get isPendingUnobservation(){return E(this.flags_,2)}set isPendingUnobservation(e){this.flags_=D(this.flags_,2,e)}get diffValue(){return+!!E(this.flags_,4)}set diffValue(e){this.flags_=D(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 Ii(e,t)}function ue(e,t){return Ii(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||ki(e)||pi(e)||P(e)||xi(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`),Ii(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.`),T(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&&(!T(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 Ie(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=Ei(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 Ie(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 A(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=Ei(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=A(`observable`),Ze=A(`observable.ref`,{enhancer_:me}),Qe=A(`observable.shallow`,{enhancer_:pe}),$e=A(`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 bi(e,tt(n),n.name)},object(e,t,n){return F(()=>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 ne(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 E(this.flags_,1)}set isComputing(e){this.flags_=D(this.flags_,1,e)}get isRunningSetter(){return E(this.flags_,2)}set isRunningSetter(e){this.flags_=D(this.flags_,2,e)}get isBeingObserved(){return E(this.flags_,4)}set isBeingObserved(e){this.flags_=D(this.flags_,4,e)}get isPendingUnobservation(){return E(this.flags_,8)}set isPendingUnobservation(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(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 ne(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 E(this.flags_,1)}set isDisposed(e){this.flags_=D(this.flags_,1,e)}get isScheduled(){return E(this.flags_,2)}set isScheduled(e){this.flags_=D(this.flags_,2,e)}get isTrackPending(){return E(this.flags_,4)}set isTrackPending(e){this.flags_=D(this.flags_,4,e)}get isRunning(){return E(this.flags_,8)}set isRunning(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(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`?Mi(t,n):Mi(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&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`),P(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=re(t);return F(()=>{let t=Ei(e,i)[O];w(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Mi(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Mi(e,t))}function er(e){let t={name:e.name_};return $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(P(e)||pi(e)||Ot(e))i=Ni(e);else if(ki(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(ki(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(Mi(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(P(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(ki(e)){var r,i;let n=e[O];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return ki(e)||!!e[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(ki(e))return e[O].keys_();if(P(e)||xi(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(ki(e))return Cr(e).map(t=>e[t]);if(P(e))return Cr(e).map(t=>e.get(t));if(xi(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(ki(e))return Cr(e).map(t=>[t,e[t]]);if(P(e))return Cr(e).map(t=>[t,e.get(t)]);if(xi(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&&!xi(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}ki(e)?e[O].set_(t,r):P(e)?e.set(t,r):xi(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){ki(e)?e[O].delete_(t):P(e)||xi(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(ki(e))return e[O].has_(t);if(P(e)||xi(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(ki(e))return e[O].get_(t);if(P(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(ki(e))return e[O].defineProperty_(t,r);n(39)}function jr(e){if(ki(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=Ni(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(P(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(xi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(ki(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Ni(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(xi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(P(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=Ei(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 F(()=>{let r=Ei(e,n)[O];w(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`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(F(()=>{let n=Ei(e,r)[O];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...w(e),...w(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;ji(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}Ai(e,r,t)}let 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)):T(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 F(()=>{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,F(()=>{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_}.${te(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_}.${te(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 _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return P(e)&&(e=new Map(e)),zr(()=>{g(e)?ee(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=vi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},P=b(`ObservableMap`,gi);function _i(e){return e[Symbol.toStringTag]=`MapIterator`,Bi(e)}function vi(e){if(x(e)||P(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let yi={};var bi=class{constructor(e,t=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),F(()=>{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 Si({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Si({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return xi(e)&&(e=new Set(e)),Array.isArray(e)||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`}},xi=b(`ObservableSet`,bi);function Si(e){return e[Symbol.toStringTag]=`SetIterator`,Bi(e)}let Ci=Object.create(null),wi=`remove`;var Ti=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_),Hi(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&&!T(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return T(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_}.${te(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);ji(this,n,e);let i=n.extend_(this,e,t,r);return i&&Ai(this,n,e),i}defineProperty_(e,t,n=!1){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=Oi(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=Oi(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_),!T(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:wi}))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:wi,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(),w(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Ei(e,t){if(t&&ki(e)&&n(`Options can't be provided for already observable objects.`),T(e,O))return Ni(e)instanceof Ti||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,O,new Ti(e,new Map,String(r),nt(t))),e}let Di=b(`ObservableObjectAdministration`,Ti);function Oi(e){return Ci[e]||(Ci[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[O]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Hi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ve(t)&&T(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Mi(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[O].atom_;if(xi(e))return e.atom_;if(P(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(ki(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(oe(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[O]))return e[O];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(oe(e)||At(e)||vn(e)||P(e)||xi(e))return e;if(e[O])return e[O];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=Mi(e,t);else if(zn(e))return e.name;else n=ki(e)||P(e)||xi(e)?Ni(e):Mi(e);return n.name_}function F(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Fi=o.toString;function Ii(e,t,n=-1){return Li(e,t,n)}function Li(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=Fi.call(e);if(o!==Fi.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=Ri(e),t=Ri(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(!Li(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(!(T(t,o)&&Li(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Ri(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||xi(e)?Array.from(e.entries()):e}let zi=globalThis.Iterator?.prototype||{};function Bi(e){return e[Symbol.iterator]=Vi,r(Object.create(zi),e)}function Vi(){return this}function Hi(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:O}),e.$mobx=O,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=bi,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=Ni,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=Mi,e.getDebugName=Pi,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=P,e.isObservableObject=ki,e.isObservableProp=Sr,e.isObservableSet=xi,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})),Y=Ee(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=xC():t.exports=SC()}))();function CC(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(CC);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(CC)}default:return!1}}function wC(e){if(Array.isArray(e))return Object.freeze(e.map(wC));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]=wC(r);return Object.freeze(t)}return e}function TC(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 EC(e){return typeof e==`string`?e:String(e)}function DC(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 OC(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 kC=class extends Error{constructor(e,t){super(t),this.variable=e}};function AC(e){return e instanceof kC?e:e instanceof Error&&e.cause!==void 0?AC(e.cause):void 0}const jC=e=>jo(e);var MC=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,jC(n)||HC(e,t,n,`initial value`),this.cell=Y.observable.box(n,{deep:!1}),this.lastChangedAt=jC(n)?null:r.now()}read(){let e=this.cell.get();if(jC(e))throw new kC(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){jC(e)||HC(this.name,this.type,e,`set value`),!(0,Y.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},NC=class{cell;constructor(e,t,n){if(this.cell=(0,Y.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_()}},PC=class{constructor(e){this.deriver=e}read(){return this.deriver()}},FC=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new NC(`Variable "${e}"`,()=>{let e=n();return HC(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},IC=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new PC(()=>{let e=n();return HC(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},LC=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=Y.observable.box(VC(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=VC(e);BC(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},RC=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new NC(`Variable "${e}"`,()=>VC(t()),BC)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function zC(e){return JSON.stringify(e)}function BC(e,t){return zC(e)===zC(t)}function VC(e){return e.kind===`ok`?{kind:`ok`,value:wC(e.value)}:e}function HC(e,t,n,r){let i=TC(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var UC=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=Y.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new MC(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new LC(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new RC(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`?FC:IC;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new PC(n);let r=new NC(`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 LC))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,Y.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,Y.runInAction)(()=>n.set(t))}runInAction(e){(0,Y.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:I(zC(e))}try{return I(String(t.read()))}catch(e){return AC(e)===void 0?I(` failed:${e instanceof Error?e.message:String(e)}`):Ao(`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,Y.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof FC||t instanceof RC)&&(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,Y.runInAction)(()=>this.nodes.set(e,t))}},WC=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?$C(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}},GC=class extends WC{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},KC=class extends WC{name=`EvalError`;kind=`EvalError`},qC=class extends KC{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=ew(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}},JC=class extends KC{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}},YC=class extends KC{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}},XC=class extends YC{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)}`}},ZC=class extends KC{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},QC=class extends KC{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function $C(e,t){let n=e.split(`
|
|
58
|
+
`)}function Sb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Cb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function wb(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function Tb(e,t,n){let r=wb(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Jv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function Eb(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 ${kb(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function Db(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ob(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function kb(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Ab(e,t,n,r){return Db(r)?(Pb(e,n,r,t.noun,new Set(Object.keys(t.fields)),jb(e,t.removed??{},n,r)),Mb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Ob(r)}`,line:J(e.source,n.split(`.`))}),null)}function jb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Fb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Mb(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 Nb=new Set;function Pb(e,t,n,r,i,a=Nb){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:J(e.source,[...t.split(`.`),o])})}function Fb(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Ib(e,t,n,r){if(!Db(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Ob(r)}`,line:J(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:J(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:J(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:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Lb(e,t,n,r){if(!Db(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Ob(r)}`,line:J(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 ${Ob(i)}`,line:J(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:J(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 Pb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Rb(e,t,n){return{json:Qb(Xb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function zb(e){return(...t)=>e()(...t)}function Bb(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:J(n.source,o.split(`.`))}),null}return a}}function Vb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>wb(e,t,r,n)}}function Hb(){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 ${Ob(i)}`,line:J(e.source,[n])});return}return i}}}}function Ub(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 ${kb(o)}`,line:J(e.source,[i])});return}return o}}}}function Wb(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 ${kb(a)}`,line:J(e.source,[r])});return}return a}}}}function Gb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Tb(e,t,r)}}function Kb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Sb(e,t,r,n)??void 0}}function qb(e,t){return D(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Jb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Sb(e,t,r,n);if(i===null)return;let a=qb(`${t}.${n}`,i);return a===null?i:Fb(e,`${t}.${n}`,a)??void 0}}}function Yb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Eb(t,n,i,r,e)}}function Xb(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 Zb(e){return Xb(e.fields)}function Qb(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function $b(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function ex(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const tx=[`claude`,`tmux`],nx=`ne .tmux.pane ""`,rx={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}},ix=Object.keys(rx),ax=ix.filter(e=>rx[e].switch.on===!0),ox={by:`request`},sx=e=>`drawing.${e}`,cx={subscribers:0,fps:0,shown:!0},lx=(e,t)=>`feeds.${e}.${t}`;function ux(e){return Object.fromEntries(ix.map(t=>[t,e(t)]))}const dx=ux(()=>cx);function fx(e){return typeof e==`string`&&Object.hasOwn(rx,e)?e:null}const px=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),mx=[...px(3,1),...px(3,.25)],hx=mx.reduce((e,{seconds:t})=>e+t,0),gx={min:15,max:600,step:15},Vee=(e,t)=>e+t,Hee=e=>e-hx,_x=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),vx=(e,t,n={})=>({spec:Yb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),yx=e=>t=>e.includes(t)?`🧪 ${t}`:t,Uee={spec:Hb(),domain:`bool`,parse:jy},Wee=e=>({spec:Ub(e),domain:e,parse:t=>My(t,e)});function bx(e,t,n,r={}){return{kind:`session`,...vx(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function xx(e,t){return{kind:`session`,...Uee,floor:e,control:t,themeDefault:!1}}function Sx(e,t,n){return{kind:`session`,...Wee(e),floor:t,control:n,themeDefault:!1}}function Cx(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const wx=e=>({kind:`text`,spec:e}),Gee={required:!1,json:{enum:[...Sy]},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: ${Sy.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return Eb(e,t,r,n,Sy)}},Kee={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=wb(e,t,r,n);return ry(i)?i:Tb(e,t,r)}},qee={required:!1,json:{anyOf:[{enum:[...fy]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ry(i)?i:Eb(e,t,r,n,fy)}},Tx=/^[^\r\n]*\S[^\r\n]*$/u,Ex=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Jee={required:!1,json:{type:`string`,pattern:Tx.source,not:{pattern:Ex.source}},parse:(e,t,n,r)=>{let i=wb(e,t,r,n);if(i===void 0||Tx.test(i)&&!Ex.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:J(e.source,[...t.split(`.`),n])})}},Yee=Object.fromEntries(ax.map(e=>[rx[e].switch.setting,xx(!1,_x(rx[e].label,`toggles`))])),Xee={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Zee={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Xee[e]})},Dx={palette:Cx(`theme`,Kee,{themes:`themes`},_x(`🎨 theme`,`door`)),preset:Cx(`preset`,Vb(),{from:`presets`},_x(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:Cx(`style`,Vb(),{from:`styles`},_x(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:Cx(`effect`,qee,{from:fy},_x(`✨ effect`,`look`)),endcaps:bx(yy,`powerline`,_x(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:bx(Ty,`accent`,_x(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:yx(q_),themeDefault:!0}),shade:bx(Ey,`middle`,_x(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:yx(I_),themeDefault:!0}),transitions:xx(!1,_x(`fade in/out`,`look`)),animationSpeed:bx(my,`1x`,_x(`speed`,`look`)),autoWrap:xx(!0,_x(`wrap`,`config`)),padding:Sx({...Ay,step:1},1,_x(`padding`,`config`)),updateNotice:xx(!0,_x(`update notice`,`config`)),menuTimeout:Sx(gx,120,_x(`menu timeout`,`config`)),renderer:bx(tx,`claude`,_x(`renderer`,`config`,{shown:nx}),{optionDomain:`renderers`,library:Zee}),...Yee,colorCompatibility:{kind:`config`,...vx(Sy,`colorCompatibilities`),spec:Gee,floor:`truecolor`},default_empty_value:wx(Vb()),default_separator:wx(Vb()),menuGlyph:wx(Jee)},Ox=Object.entries(Dx),kx=Ox.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Qee=Ox.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Ax=Ox.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),$ee=Ox.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function jx(e){return Dx[e]}const Mx=e=>jx(e).floor;function Nx(e){let t=Dx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const Px=e=>`${e}.effective`,ete=e=>{let t=Dx[e];return t.kind===`selection`?t.sessionKey:e},Fx=Object.fromEntries(Qee.map(e=>{let t=ete(e);return[t,{configKey:e,sessionKey:t,effectiveVar:Px(t),...Dx[e].control}]})),Ix=Object.keys(Fx),Lx=Object.values(Fx),Rx=kx.filter(e=>Dx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:Px(e)})),tte=new Set(Rx.map(e=>e.configKey)),zx=new Map([...Lx,...Rx].map(e=>[e.configKey,e.effectiveVar])),Bx=new Map(Lx.map(e=>[e.sessionKey,e.effectiveVar]));function Vx(e){return Object.fromEntries(Ix.map(t=>[t,e(t)]))}const Hx=new Map(Ix.map(e=>[Fx[e].sessionKey,e])),Ux=new Map;function Wx(e){let t=Kx(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 Gx(e,t){return e===`bar`?t:Wx(e)}function Kx(e){let t=Ux.get(e);if(t!==void 0)return t;let n=bee(e);return n===null?null:(Ux.set(e,n),n)}function qx(e,t){return nte(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Bd(e,t))}const nte=S_();function Jx(e){let t=Kx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Yx(e,t,n){let r=Jx(e);return r===null?(n(dy(t,`palette`,`"${e}" names no installed theme${Jv(e)}`)),Xx()):r}function rte(e,t,n){return iy(e,t,n,Xx(),Jx)}function Xx(){return{kind:`decided`,name:Yv,value:Wx(Yv)}}const Zx=/^[A-Za-z_][A-Za-z0-9_]*$/;function ite(e){return`#${e+1}`}const Qx={rows:{}};function $x(e){return`rows`in e}function eS(e){return Object.fromEntries(e.map((e,t)=>[ite(t),e]))}function ate(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 tS(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function nS(e){return $x(e)?tS(e):e}function*rS(e,t){if(!$x(e)){yield*Hy(e,t);return}yield[tS(e),t];for(let[n,r]of Object.entries(e.rows))yield*Hy(r,`${t}.rows.${n}`)}function iS(e,t){return $x(e)?{...t,...e,rows:{...t.rows,...e.rows}}:ate(e)}function aS(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...zy(tS(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||Fy(e)===t.id)))return e;let i=r.find(e=>Fy(e)===n);if(i!==void 0)return oS(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,sS(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]))}}:oS(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function oS(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function sS(e,t,n,r){if(e.kind===`segment`&&Fy(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`?cS(e,t,n,r):lS(e,t,n,r)}function cS(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&Fy(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`?cS(a,t,n,r):lS(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function lS(e,t,n,r){let i=!1,a=Ry(e,e=>{let a=cS(e,t,n,r);return i=a!==null,a??e});return i?a:null}function uS(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 dS=`default`,fS={};function pS(e){return[...new Set([dS,...Object.keys(e)])]}function mS(e,t,n){return ty(void 0,e,t,dS,n)}function hS(e,t){let n={[dS]:fS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${dS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function gS(e,t){let n=hS(e.presets,t).root??Qx;return{node:tS(iS(n,e.root)),path:uS(n)?`presets.${t}.root`:`root`}}function _S(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=aS(e.root,t),i=Object.entries(e.presets).filter(([,e])=>uS(e.root??Qx)).map(([n,r])=>({name:n,preset:r,...aS(iS(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:tS(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>vS(e,`${t} (in ${n.join(`, `)})`)))}}function vS(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function yS(e,t){return{...e.globals,...hS(e.presets,t).globals}}const bS=new Map;function xS(e,t,n={}){bS.set(e,{permanent:!0,resolve:t,...n})}xS(`themes`,()=>Zv(),{paletteOf:e=>Wx(e)});const SS=`placementThemes`;xS(SS,Qv,{paletteOf:(e,t)=>Gx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of $ee)xS(e,()=>t,{library:n,labelOf:r});function CS(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>qx(n.basePalette,e.styles[t])}],[`presets`,{members:pS(e.presets)}]])}function wS(e){return[...new Set([...bS.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=bS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(DS(e,t))}const ES=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function DS(e,t){let n=ES.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${wS(t).join(`, `)})`}const OS=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function kS(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*AS(e){let t=[];jS(e,(e,n)=>(t.push([n,e]),e)),yield*t}function jS(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 MS(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const NS=[`plugins`,`repo`];function PS({scope:e,name:t}){return`${e}.${t}`}function FS(e){return t=>t===e||t.startsWith(`${e}.`)}const IS=`self`;function LS(e){return NS.find(t=>e===t||e.startsWith(`${t}.`))}function RS(e,t){let n=LS(e);if(n===void 0||n===e)return``;let r=NS.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)`}const zS=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*BS(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 VS=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,HS=RegExp(`^(?:(\\$)(?:\\.(${VS}))?|\\.(${VS})?)(?=[\\s)]|$)`);function US(e,t,n){let r=HS.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 WS=/^(\w+)\b\s*([\s\S]*)$/;function*GS(e,t){let n=[t];for(let r of BS(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=WS.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:US(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(US(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const KS=/(?<![.$])\btemplate\s+$/;function*qS(e,t,n){let r=0;for(let i of[...e.matchAll(zS)]){let a=i.index+i[0].length;KS.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:US(e.slice(a),t,n),index:i.index}),r=a}}function*JS(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...GS(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...qS(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 YS(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const XS=new WeakMap;function ZS(e,t){let n=XS.get(t);return n===void 0&&(n=YS(e=>[...JS(e,t)]),XS.set(t,n)),n(e)}const QS=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${VS})`,`g`);function*$S({code:e,dot:t,root:n}){let r=e.replace(zS,``);for(let e of[...r.matchAll(QS)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function eC(e,t){let n=new Map;for(let r of ZS(e,t))for(let e of $S(r))n.has(e)||n.set(e,r.via);return n}const tC=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,nC={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*rC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(zS)]){let a=e.slice(t,i.index),o=tC.exec(a);o===null?a.trim()!==``&&(n=0):(n=nC[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 iC(e,t){let n=new Map;for(let{code:r,via:i}of ZS(e,t))for(let{name:e,site:t}of rC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const aC=RegExp(`^${Vi}://([a-z][a-z0-9-]*)`);function oC(e,t){let n=new Map;for(let{code:r,via:i}of ZS(e,t))for(let e of r.matchAll(zS)){let t=aC.exec(e[0].slice(1,-1))?.[1];if(t===void 0)continue;let r=`${t}\0${i??`\0`}`;n.has(r)||n.set(r,{verb:t,via:i})}return[...n.values()]}const sC=e=>Object.keys(nC).filter(t=>nC[t]>=e).join(`|`),cC=RegExp(`(?<![\\w.$])(?:(?:${sC(1)})\\s+|(?:${sC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function lC(e,t){for(let{code:n}of ZS(e,t))if(cC.test(n.replace(zS,`""`)))return!0;return!1}const uC=/(?<![\w.$])[A-Za-z_]\w*/g;function dC(e,t){let n=new Set;for(let{code:r}of ZS(e,t))for(let[e]of r.replace(zS,``).matchAll(uC))n.add(e);return n}function fC(e,t){return new Set([...pC(e,t)].filter(e=>Object.hasOwn(t,e)))}function pC(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of ZS(e,t))for(let{name:e}of qS(r,i,a))n.add(e);return n}const mC=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function hC(e,t,n){let r=mC(t),i=FS(t),a=[];for(let{dot:t,block:n}of GS(e,``)){let e=n.text.replace(zS,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[...qS(n.text,t,``),...rC(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*gC(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*_C(e){for(let[t,n]of gC(e))yield[t,n]}function vC(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 yC(e,t){return vC(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function bC(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),xC(r)&&n.add(e)};for(let[t,n]of _C(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function xC(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&Wy(e.parse)===`json`}var SC=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,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(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 ee(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 w(e,t){return{t:e,i:t,o:te,u:ne}}function te(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,re(e,0,0,n,!1,!1)),2)}function ne(e,t,n,r){let i=re(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function T(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 re(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 E(e,t){return{t:e,i:t,o:D,u:ie}}function D(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&&(A(),!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 Ie(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 A(){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(),Ie(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=E(cn),un=ge(E(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return O(ln,e,t);if(o(e))return ge(E(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),A())}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=w(`flow`),Wn=w(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return T(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,T),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),Ie(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||{})}})),CC=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=T(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 ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let w=Reflect.ownKeys;function te(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ne(e){return e===null?null:typeof e==`object`?``+e:e}function T(e,t){return o.hasOwnProperty.call(e,t)}let re=Object.getOwnPropertyDescriptors;function E(e,t){return!!(e&t)}function D(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 E(this.flags_,1)}set isBeingObserved(e){this.flags_=D(this.flags_,1,e)}get isPendingUnobservation(){return E(this.flags_,2)}set isPendingUnobservation(e){this.flags_=D(this.flags_,2,e)}get diffValue(){return+!!E(this.flags_,4)}set diffValue(e){this.flags_=D(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 Ii(e,t)}function ue(e,t){return Ii(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||ki(e)||pi(e)||P(e)||xi(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`),Ii(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.`),T(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&&(!T(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 Ie(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=Ei(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 Ie(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 A(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=Ei(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=A(`observable`),Ze=A(`observable.ref`,{enhancer_:me}),Qe=A(`observable.shallow`,{enhancer_:pe}),$e=A(`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 bi(e,tt(n),n.name)},object(e,t,n){return F(()=>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 ne(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 E(this.flags_,1)}set isComputing(e){this.flags_=D(this.flags_,1,e)}get isRunningSetter(){return E(this.flags_,2)}set isRunningSetter(e){this.flags_=D(this.flags_,2,e)}get isBeingObserved(){return E(this.flags_,4)}set isBeingObserved(e){this.flags_=D(this.flags_,4,e)}get isPendingUnobservation(){return E(this.flags_,8)}set isPendingUnobservation(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(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 ne(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 E(this.flags_,1)}set isDisposed(e){this.flags_=D(this.flags_,1,e)}get isScheduled(){return E(this.flags_,2)}set isScheduled(e){this.flags_=D(this.flags_,2,e)}get isTrackPending(){return E(this.flags_,4)}set isTrackPending(e){this.flags_=D(this.flags_,4,e)}get isRunning(){return E(this.flags_,8)}set isRunning(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(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`?Mi(t,n):Mi(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&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`),P(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=re(t);return F(()=>{let t=Ei(e,i)[O];w(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Mi(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Mi(e,t))}function er(e){let t={name:e.name_};return $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(P(e)||pi(e)||Ot(e))i=Ni(e);else if(ki(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(ki(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(Mi(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(P(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(ki(e)){var r,i;let n=e[O];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return ki(e)||!!e[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(ki(e))return e[O].keys_();if(P(e)||xi(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(ki(e))return Cr(e).map(t=>e[t]);if(P(e))return Cr(e).map(t=>e.get(t));if(xi(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(ki(e))return Cr(e).map(t=>[t,e[t]]);if(P(e))return Cr(e).map(t=>[t,e.get(t)]);if(xi(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&&!xi(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}ki(e)?e[O].set_(t,r):P(e)?e.set(t,r):xi(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){ki(e)?e[O].delete_(t):P(e)||xi(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(ki(e))return e[O].has_(t);if(P(e)||xi(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(ki(e))return e[O].get_(t);if(P(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(ki(e))return e[O].defineProperty_(t,r);n(39)}function jr(e){if(ki(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=Ni(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(P(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(xi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(ki(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Ni(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(xi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(P(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=Ei(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 F(()=>{let r=Ei(e,n)[O];w(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`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(F(()=>{let n=Ei(e,r)[O];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...w(e),...w(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;ji(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}Ai(e,r,t)}let 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)):T(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 F(()=>{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,F(()=>{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_}.${te(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_}.${te(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 _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return _i({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return P(e)&&(e=new Map(e)),zr(()=>{g(e)?ee(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=vi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},P=b(`ObservableMap`,gi);function _i(e){return e[Symbol.toStringTag]=`MapIterator`,Bi(e)}function vi(e){if(x(e)||P(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let yi={};var bi=class{constructor(e,t=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),F(()=>{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 Si({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Si({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return xi(e)&&(e=new Set(e)),Array.isArray(e)||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`}},xi=b(`ObservableSet`,bi);function Si(e){return e[Symbol.toStringTag]=`SetIterator`,Bi(e)}let Ci=Object.create(null),wi=`remove`;var Ti=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_),Hi(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&&!T(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return T(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_}.${te(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);ji(this,n,e);let i=n.extend_(this,e,t,r);return i&&Ai(this,n,e),i}defineProperty_(e,t,n=!1){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=Oi(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=Oi(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_),!T(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:wi}))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:wi,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(),w(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Ei(e,t){if(t&&ki(e)&&n(`Options can't be provided for already observable objects.`),T(e,O))return Ni(e)instanceof Ti||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,O,new Ti(e,new Map,String(r),nt(t))),e}let Di=b(`ObservableObjectAdministration`,Ti);function Oi(e){return Ci[e]||(Ci[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[O]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Hi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ve(t)&&T(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Mi(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[O].atom_;if(xi(e))return e.atom_;if(P(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(ki(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(oe(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[O]))return e[O];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(oe(e)||At(e)||vn(e)||P(e)||xi(e))return e;if(e[O])return e[O];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=Mi(e,t);else if(zn(e))return e.name;else n=ki(e)||P(e)||xi(e)?Ni(e):Mi(e);return n.name_}function F(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Fi=o.toString;function Ii(e,t,n=-1){return Li(e,t,n)}function Li(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=Fi.call(e);if(o!==Fi.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=Ri(e),t=Ri(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(!Li(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(!(T(t,o)&&Li(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Ri(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||xi(e)?Array.from(e.entries()):e}let zi=globalThis.Iterator?.prototype||{};function Bi(e){return e[Symbol.iterator]=Vi,r(Object.create(zi),e)}function Vi(){return this}function Hi(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:O}),e.$mobx=O,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=bi,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=Ni,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=Mi,e.getDebugName=Pi,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=P,e.isObservableObject=ki,e.isObservableProp=Sr,e.isObservableSet=xi,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})),Y=Ee(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=SC():t.exports=CC()}))();function wC(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(wC);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(wC)}default:return!1}}function TC(e){if(Array.isArray(e))return Object.freeze(e.map(TC));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]=TC(r);return Object.freeze(t)}return e}function EC(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 DC(e){return typeof e==`string`?e:String(e)}function OC(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 kC(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 AC=class extends Error{constructor(e,t){super(t),this.variable=e}};function jC(e){return e instanceof AC?e:e instanceof Error&&e.cause!==void 0?jC(e.cause):void 0}const MC=e=>jo(e);var NC=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,MC(n)||UC(e,t,n,`initial value`),this.cell=Y.observable.box(n,{deep:!1}),this.lastChangedAt=MC(n)?null:r.now()}read(){let e=this.cell.get();if(MC(e))throw new AC(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){MC(e)||UC(this.name,this.type,e,`set value`),!(0,Y.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},PC=class{cell;constructor(e,t,n){if(this.cell=(0,Y.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_()}},FC=class{constructor(e){this.deriver=e}read(){return this.deriver()}},IC=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new PC(`Variable "${e}"`,()=>{let e=n();return UC(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},LC=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new FC(()=>{let e=n();return UC(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},RC=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=Y.observable.box(HC(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=HC(e);VC(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},zC=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new PC(`Variable "${e}"`,()=>HC(t()),VC)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function BC(e){return JSON.stringify(e)}function VC(e,t){return BC(e)===BC(t)}function HC(e){return e.kind===`ok`?{kind:`ok`,value:TC(e.value)}:e}function UC(e,t,n,r){let i=EC(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var WC=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=Y.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new NC(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new RC(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new zC(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`?IC:LC;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new FC(n);let r=new PC(`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 RC))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,Y.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,Y.runInAction)(()=>n.set(t))}runInAction(e){(0,Y.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:I(BC(e))}try{return I(String(t.read()))}catch(e){return jC(e)===void 0?I(` failed:${e instanceof Error?e.message:String(e)}`):Ao(`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,Y.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof IC||t instanceof zC)&&(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,Y.runInAction)(()=>this.nodes.set(e,t))}},GC=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?ew(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}},KC=class extends GC{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},qC=class extends GC{name=`EvalError`;kind=`EvalError`},JC=class extends qC{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=tw(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}},YC=class extends qC{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}},XC=class extends qC{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}},ZC=class extends XC{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 qC{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},$C=class extends qC{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function ew(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 tw(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:nw(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 nw(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 rw(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const iw=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`]]),aw={left:`{{`,right:`}}`};var ow=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=aw){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 KC(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&&sw(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);sw(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);sw(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(;sw(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`;sw(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&&(lw(e)||cw(e)&&lw(this.src[this.offset+1]??``)||e===`.`&&lw(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&mw(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(cw(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);uw(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);dw(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);fw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;lw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);lw(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),cw(this.src[this.offset]??``)&&this.advanceBy(1);lw(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return uw(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);hw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&mw(this.src[this.offset+1]??``);)for(this.advanceBy(1);hw(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),!mw(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;hw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&mw(this.src[this.offset+1]??``);)for(this.advanceBy(1);hw(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(;hw(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=iw.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 GC(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Mw(e,t,n){let r=jw(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new GC(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function Nw(e,t){if(t(e)!==!1)for(let n of Pw(e))Nw(n,t)}function Pw(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 nw(e)}}const Fw=Symbol(`go-template-js.MISSING`);function Iw(e,t){if(e==null)return Fw;if(e instanceof Map)return e.has(t)?e.get(t):Fw;if(Array.isArray(e))return Fw;if(typeof e==`object`){let n=e;return t in n?n[t]:Fw}return Fw}function Lw(e,t){let n=e;for(let e of t){if(n===Fw)return Fw;n=Iw(n,e)}return n}function Rw(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)=>Rw(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)||!Rw(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=>Rw(e[n],t[n])):!1}return!1}const zw=new WeakSet;function Bw(e){return zw.add(e),e}function Vw(e){return zw.has(e)}function Hw(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 Uw(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Kw(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Kw(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>qw(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>qw(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>qw(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>qw(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Jw(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Yw(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Zw(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>eT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${eT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>lT(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>fT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>fT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>rT(eT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>oT(eT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>cT(eT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Hw(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Ww(){return{and:Bw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Hw(t))return t;return t}}),or:Bw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Hw(t))return t;return t}})}}function Gw(e,t){return{...Uw(e,t),...Ww()}}function Kw(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Rw(e,t)}function qw(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 Jw(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Yw(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Xw(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 ${Qw(t)}`);return e[t]}throw Error(`index: cannot index ${Qw(e)}`)}function Xw(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 ${$w(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Zw(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]=Xw(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 Qw(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function $w(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 eT(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+=tT(a,t),r=o}return n}function tT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const nT={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function rT(e){return e.replace(/[\0"'&<>]/g,e=>nT[e]??e)}const iT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},aT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function oT(e){let t=``;for(let n of e){let e=iT[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!aT.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const sT=new TextEncoder;function cT(e){let t=``,n=sT.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 lT(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+=uT(l??``,u,d,n,r),o=c+1}return i}function uT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?dT(t,n):dT(t,tT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${$w(n)}=${tT(n,r)})`:dT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return dT(t,fT(n,r,i));case`q`:return dT(t,JSON.stringify(tT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${$w(n)}=${tT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return dT(t,Number(n).toFixed(i))}case`t`:return dT(t,Hw(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 dT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${$w(n)}=${tT(n,r)})`:typeof n==`bigint`?dT(t,n.toString(16)):dT(t,Math.trunc(n).toString(16));default:return`%!${e}(${$w(n)}=${tT(n,r)})`}}function dT(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 fT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>fT(e,t,n)).join(` `)}]`:e instanceof Map?pT([...e.entries()],t,n):mT(e)?pT(Object.entries(e),t,n):String(e)}function pT(e,t,n){let r=e=>fT(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 mT(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 hT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function gT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function _T(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 vT(e,t,n){e.vars.set(t,n)}const yT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],bT=new Set([`default`,`zero`,`error`]);function xT(e){if(e===void 0)return`default`;if(bT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${ST(e)}`)}function ST(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 CT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${ST(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${ST(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${ST(e.right)}`);return{left:e.left,right:e.right}}}function wT(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function TT(e){let t=new Set(yT);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 ${yT.join(`, `)}`)}),wT(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 ET=Object.freeze({kind:`break`}),DT=Object.freeze({kind:`continue`}),OT={kind:`none`};let kT;(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{kT=(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 AT(e){let t=new Set,n=e=>{Nw(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 jT={kind:`dynamic`};function MT(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=$T(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:jT}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return jT;let t=e.cmds[0];if(t===void 0)return jT;let n=t.args[0];return n===void 0||n.type!==`Identifier`?jT:{kind:`call`,name:n.ident,args:t.args.slice(1).map(MT)}}default:return jT}}function NT(e){let t=[],n=e=>{Nw(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(MT);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 PT=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??HT,this.isT=e.isT??FT,this.missingKey=xT(e.missingKey),this.delims=CT(e.delims),this.funcs=TT({...Gw(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=yw(e,this.delims,t);return kT(n.source,e=>this.evalParsed(n,e),n.defines,AT(n),NT(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=hT(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 ET;case`Continue`:throw DT;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 KC(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:nw(e)}}evalIf(e,t,n){Hw(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(Hw(r)){let i=gT(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=XT(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=gT(t,o);if(i.length===1)vT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;vT(a,e,r),vT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===DT)continue;throw e}}}catch(e){if(e===ET)return;throw e}}evalTemplateInvoke(e,t,n){let r=_w(n.defines,e.name);if(!r)throw new KC(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=gT(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=gT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=_w(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 KC(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,OT);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)vT(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 KC(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new KC(`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 qC(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Vw(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){LT(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof YC?new YC(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof QC?new QC(t.message,r,{source:i.source}):t instanceof WC?t:new KC(`error calling ${e}: ${JT(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 $T(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 qC(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 KC(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Lw(e,t);if(i!==Fw)return i;if(this.missingKey===`error`)throw new ZC(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=_T(t,i);if(!a.found)throw new KC(`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(fT(e,this.toString,this.isT)))}};const FT=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function IT(e){return new PT(e)}function LT(e,t,n,r,i,a=HT,o=VT,s=FT){let{argTypes:c,arity:l}=t,u=RT(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new JC(e,u,n.length,r,{source:i});let d=zT(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!BT(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new XC(e,t+1,l,r,{source:i}):new YC(e,t+1,qT(c),YT(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(!WT(n[f],l))throw new YC(e,t+1,`${qT(`ordered`)} of the same kind as ${YT(n[f])}`,YT(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!GT(n[p],l))throw new YC(e,t+1,`${qT(`comparable`)} of the same kind as ${YT(n[p])}`,YT(l),r,{source:i})}}}function RT(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 zT(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 BT(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 mT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||mT(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||mT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||mT(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 UT(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function VT(e){return e}function HT(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 YC(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,YT(e),{line:0,column:0,offset:0})}function UT(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function WT(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function GT(e,t){let n=KT(e),r=KT(t);return n===`nil`||r===`nil`?!0:n===r}function KT(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 qT(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 JT(e){return e instanceof Error?e.message:String(e)}function YT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function XT(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?ZT([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?ZT(Object.entries(e)):[]}function ZT(e){return[...e].sort((e,t)=>QT(e[0],t[0]))}function QT(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 $T(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 eE(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function tE(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 nE(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 rE(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=nE(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 iE(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=nE(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 aE(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 oE(e){return JSON.stringify(e)??`null`}function sE(){return{atoi:{fn:e=>eE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>rE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>iE(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>tE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>aE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>oE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const cE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function lE(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*cE[a],n=n.slice(e[0].length)}return t?-r:r}function uE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<cE.us?`${Math.floor(n)}ns`:n<cE.ms?dE(n,cE.us,3,`µs`):n<cE.s?dE(n,cE.ms,6,`ms`):fE(n),t?`-${r}`:r}function dE(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 fE(e){let t=Math.floor(e/cE.h);e-=t*cE.h;let n=Math.floor(e/cE.m);e-=n*cE.m;let r=Math.floor(e/cE.s),i=e-r*cE.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 pE(e){return e*cE.s}function mE(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 hE(e,t){let n=t().getTime()-mE(e).getTime();return uE(Math.round(n/1e3)*1e9)}const gE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],_E=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],vE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],yE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function bE(e){return e<10?`0${e}`:String(e)}function xE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function SE(e){return e<10?` ${e}`:String(e)}function CE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${bE(Math.floor(n/60))}${bE(n%60)}`}function wE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${bE(Math.floor(n/60))}:${bE(n%60)}`}function TE(e){return`${e>=0?`+`:`-`}${bE(Math.floor(Math.abs(e)/60))}`}function EE(e){return e===0?`Z`:CE(e)}function DE(e){return e===0?`Z`:wE(e)}function OE(e){return e===0?`Z`:TE(e)}function kE(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=>`.${kE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=kE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${kE(e.ms,6,!1)}`],[`.999999`,e=>{let t=kE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${xE(e.ms)}`],[`.999`,e=>{let t=xE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>gE[e.month-1]??`January`],[`Monday`,e=>vE[e.weekday]??`Monday`],[`Z07:00`,e=>DE(e.offsetMinutes)],[`-07:00`,e=>wE(e.offsetMinutes)],[`Z0700`,e=>EE(e.offsetMinutes)],[`-0700`,e=>CE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>_E[e.month-1]??`Jan`],[`Mon`,e=>yE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>TE(e.offsetMinutes)],[`Z07`,e=>OE(e.offsetMinutes)],[`15`,e=>bE(e.hour)],[`01`,e=>bE(e.month)],[`02`,e=>bE(e.day)],[`_2`,e=>SE(e.day)],[`03`,e=>bE(e.hour12)],[`04`,e=>bE(e.minute)],[`05`,e=>bE(e.second)],[`06`,e=>bE(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 jE(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 ME={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function NE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const PE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function FE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=NE(new Intl.DateTimeFormat(`en-US`,{...ME,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=NE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=IE(NE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=PE.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 IE(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 LE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function RE(e,t){return jE(e,FE(mE(t),LE()))}function zE(e,t,n){return jE(e,FE(mE(t),n))}function BE(e,t){let n=mE(t),r=lE(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function VE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:uE(pE(t))}return typeof e==`bigint`?uE(pE(Number(e))):typeof e==`number`?uE(pE(e)):`0s`}const HE=36e11*24*365,UE=36e11*24*30,WE=36e11*24,GE=36e11,KE=6e10,qE=1e9;function JE(e){let t=lE(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>HE?`${Math.floor(n/HE)}y`:n>UE?`${Math.floor(n/UE)}mo`:n>WE?`${Math.floor(n/WE)}d`:n>GE?`${Math.floor(n/GE)}h`:n>KE?`${Math.floor(n/KE)}m`:n>qE?`${Math.floor(n/qE)}s`:`0s`}function YE(e){let t=FE(mE(e),LE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function XE(e,t){let n=FE(mE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function ZE(e){return e()}const QE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],$E=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function eD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function tD(e,t,n){return[e.slice(t,t+n),t+n]}function nD(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 rD(e,t){for(let[n,r]of QE.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function iD(e,t){for(let[n,r]of $E.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function aD(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 oD(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 sD(e,t){if(e[t]===` `){let[n,r]=nD(e,t+1,1,1);return[n,r]}return nD(e,t,1,2)}function cD(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]=nD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=nD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=nD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function lD(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]=nD(e,t+1,2,2);return[n*r*60,i]}return cD(e,t,n)}function uD(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 dD(e,t,n){let[r,i]=tD(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function fD(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=rD(t,n);return i.month=e,[r,i]}case`Monday`:return[aD(t,n),i];case`Jan`:{let[e,r]=iD(t,n);return i.month=e,[r,i]}case`Mon`:return[oD(t,n),i];case`2006`:{let[e,r]=nD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=nD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=nD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=nD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=sD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=nD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=nD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=nD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=nD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=nD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=nD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=nD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=nD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=nD(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[uD(t,n),i];case`-0700`:{let[e,r]=cD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=cD(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]=nD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=lD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=lD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=lD(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]=dD(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]=dD(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]=dD(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 pD=`.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 mD(e,t){let n=0,r=0,i=eD();for(;n<e.length;){let a=!1;for(let o of pD)if(e.startsWith(o,n)){let[e,s]=fD(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 hD(e,t){return mD(e,t)}function gD(e){return String(Math.floor(mE(e).getTime()/1e3))}function _D(e=()=>new Date){return{now:{fn:()=>ZE(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>RE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>zE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>BE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>YE(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>XE(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>VE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>JE(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>hD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>hE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>gD(e),argTypes:[`value`],arity:{kind:`exact`}}}}function vD(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 yD(...e){for(let t of e)if(!vD(t))return t}function bD(e,t){return vD(t)?e:t}function xD(e){return JSON.parse(e)}function SD(e,t,n){return Hw(n)?e:t}function CD(e){return JSON.stringify(e)??`null`}function wD(e){return JSON.stringify(e,null,2)??`null`}function TD(){return{default:{fn:(e,t)=>bD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>vD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>yD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>SD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>xD(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>CD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>wD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function ED(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function DD(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 ED(...t)}function OD(e,t){return e[t]}function kD(e,t){return t in e}function AD(e){return Object.keys(e)}function jD(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 MD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function ND(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 PD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function FD(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function ID(e,t,n){return e[t]=n,e}function LD(e,t){return delete e[t],e}function RD(e){return Object.values(e)}function zD(){return{dict:{fn:(...e)=>ED(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>OD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>ID(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>LD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>AD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>RD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>FD(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>PD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>ND(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>kD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>jD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>MD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function BD(e){throw new QC(e)}function VD(){return{fail:{fn:e=>BD(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 HD(...e){for(let t of e)if(vD(t))return!1;return!0}function UD(...e){for(let t of e)if(!vD(t))return!0;return!1}function WD(e,t){return[...e,t]}function GD(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 KD(e){return e.filter(e=>!vD(e))}function qD(...e){let t=[];for(let n of e)t.push(...n);return t}const JD={line:0,column:0,offset:0};function YD(e,t,n,r){return new YC(e,t,n,r,JD)}function XD(...e){if(e.length<3)throw YD(`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(!QD(t))throw YD(`dig`,e.length-1,`dict`,$D(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw YD(`dig`,e,`string`,$D(r[e]));return ZD(t,n,r,e.length)}function ZD(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(!QD(a))throw YD(`dig`,r-1,`dict at intermediate key`,$D(a));return ZD(a,t,n.slice(1),r)}function QD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function $D(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function eO(e){return e[0]}function tO(e,t){return t.some(t=>Rw(t,e))}function nO(e){return e.slice(0,-1)}function rO(e){return e[e.length-1]}function iO(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function aO(...e){return e}function oO(e,t){return[t,...e]}function sO(e){return e.slice(1)}function cO(e){return[...e].reverse()}function lO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function uO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function dO(e){let t=[];for(let n of e)t.some(e=>Rw(e,n))||t.push(n);return t}function fO(e,...t){return e.filter(e=>!t.some(t=>Rw(t,e)))}function pO(){return{list:{fn:(...e)=>aO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>eO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>rO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>sO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>nO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>iO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>cO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>dO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>fO(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>tO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>KD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>lO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>qD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>GD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>oO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>WD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>uO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>WD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>aO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>XD(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>HD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>UD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function mO(...e){return e.reduce((e,t)=>e+t,0)}function hO(e){return e+1}function gO(e){return e+1}function _O(...e){return e.reduce((e,t)=>e+t,0)}function vO(e){return Math.ceil(e)}function yO(e,t){return Math.trunc(e/t)}function bO(e,...t){return t.reduce((e,t)=>e/t,e)}function xO(e){return Math.floor(e)}function SO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function CO(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function wO(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function TO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function EO(e,t){return e%t}function DO(...e){return e.reduce((e,t)=>e*t,1)}function OO(...e){return e.reduce((e,t)=>e*t,1)}function kO(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 jO(...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 MO(e,t){return e-t}function NO(e,...t){return t.reduce((e,t)=>e-t,e)}function PO(e){return AO(0,e,e<0?-1:1)}function FO(){return{add:{fn:(...e)=>mO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>MO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>DO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>yO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>EO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>wO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>SO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>xO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>vO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>kO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>_O(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>NO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>OO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>bO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>hO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>gO(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>CO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>TO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>SO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>jO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>PO(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 IO(e){return Array.from(e)}function LO(e,t){return e===``?IO(t):t.split(e)}function RO(e,t){let n=IO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function zO(e,t,n){let r=IO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const BO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},VO=/^[-_\s]$/,HO=/^\p{P}$/u,UO=/^\p{L}$/u,WO=/^\p{Lu}$/u,GO=/^\p{N}$/u;function KO(e){return e!==void 0&&VO.test(e)}function qO(e){return e!==void 0&&UO.test(e)}function JO(e){return e!==void 0&&WO.test(e)}function YO(e){return e!==void 0&&GO.test(e)}function XO(e){return e!==void 0&&HO.test(e)}function ZO(e,t){if(t>=e.length)return{word:{wt:BO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(KO(n)){for(;r<e.length&&KO(e[r]);)r++;return{word:{wt:BO.Connector,text:e.slice(t,r).join(``)},next:r}}if(XO(n)){for(;r<e.length&&XO(e[r]);)r++;return{word:{wt:BO.Punct,text:e.slice(t,r).join(``)},next:r}}if(JO(n)){if(r>=e.length)return{word:{wt:BO.UpperCase,text:n},next:r};if(JO(e[r])){let n=r;for(;n<e.length&&JO(e[n]);)n++;return n<e.length&&qO(e[n])?{word:{wt:BO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:BO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(qO(e[r])){let n=r+1;for(;n<e.length&&qO(e[n])&&!JO(e[n]);)n++;return{word:{wt:BO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:BO.UpperCase,text:n},next:r}}if(qO(n)){for(;r<e.length&&qO(e[r])&&!JO(e[r]);)r++;return{word:{wt:BO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(YO(n)){for(;r<e.length&&YO(e[r]);)r++;return{word:{wt:BO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!KO(e[r])&&!qO(e[r])&&!YO(e[r])&&!XO(e[r]);)r++;return{word:{wt:BO.Other,text:e.slice(t,r).join(``)},next:r}}function QO(e,t,n){if(t.wt!==BO.UpperCase&&t.wt!==BO.Connector){e.push(t.text);return}for(let r of t.text)KO(r)?e.push(n):JO(r)?e.push(r.toLowerCase()):e.push(r)}function $O(e,t){if(e.length===0)return``;let n=IO(e),r=[],{word:i,next:a}=ZO(n,0);for(;a<n.length;){i.wt!==BO.Connector&&QO(r,i,t);let e=i,o=i;if({word:i,next:a}=ZO(n,a),e.wt===BO.Number){for(;i.wt===BO.Alphabet||i.wt===BO.Number;)QO(r,i,t),{word:i,next:a}=ZO(n,a);i.wt!==BO.Invalid&&i.wt!==BO.Punct&&i.wt!==BO.Connector&&r.push(t);continue}if(e.wt===BO.Connector){QO(r,o,t);continue}if(e.wt===BO.Punct)continue;if(i.wt!==BO.Number){i.wt!==BO.Connector&&i.wt!==BO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=ZO(n,a),i.wt!==BO.Alphabet){QO(r,s,t),i.wt!==BO.Connector&&i.wt!==BO.Punct&&r.push(t);continue}for(r.push(t),QO(r,s,t);i.wt===BO.Alphabet||i.wt===BO.Number;)QO(r,i,t),{word:i,next:a}=ZO(n,a);i.wt!==BO.Invalid&&i.wt!==BO.Connector&&i.wt!==BO.Punct&&r.push(t)}return QO(r,i,t),r.join(``).toLowerCase()}function ek(e){if(e.length===0)return``;let t=IO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!KO(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++,KO(i)&&KO(e)){n.push(e);continue}KO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function tk(e){return ek(e)}function nk(...e){return e.join(` `)}function rk(e,t){return t.includes(e)}function ik(e,t){return t.startsWith(e)}function ak(e,t){return t.endsWith(e)}function ok(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 sw(e){return e===` `||e===` `||e===`\r`||e===`
|
|
65
|
+
`}function cw(e){return e===`+`||e===`-`}function lw(e){return e>=`0`&&e<=`9`}function uw(e){return lw(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function dw(e){return e>=`0`&&e<=`7`}function fw(e){return e===`0`||e===`1`}function pw(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function mw(e){return pw(e)||e===`_`}function hw(e){return mw(e)||lw(e)}let gw,_w;function vw(e,t){return _w(e,t)}var yw=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{gw=(t,n)=>new e(t,n),_w=(e,t)=>e.#e.get(t)??(e.#t&&_w(e.#t,t))}has(e){return _w(this,e)!==void 0}};function bw(e,t,n=yw.EMPTY){return new xw(e,t,n).parseTemplate()}var xw=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new ow(e,t):new ow(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:ww(n)});return n}errAt(e,t,n={}){return new KC(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 ${ww(e)}`,{found:ww(e)})}return{root:e,defines:gw(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=Cw(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 Sw(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${ww(n)} at top level`,{found:ww(n)})}return Sw(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 KC(`{{${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 KC(`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:ww(e)});return Mw(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(!Tw(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:ww(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=[Ew(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(Ew(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;Tw(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 Ew(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Mw(e.value,e.pos,this.source)};case`Number`:return Ow(e);case`Char`:return kw(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 ${ww(e)}`,{expected:`command argument`,found:ww(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 Sw(e,t){return{type:`List`,pos:e,nodes:t}}function Cw(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function ww(e){return e.type===`EOF`?`end of input`:e.value||e.type}function Tw(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 Ew(e){return{type:`Variable`,pos:e.pos,idents:Dw(e.value)}}function Dw(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function Ow(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=Aw(i);return{...s,intValue:e}}if(a){let e=jw(i);return{...s,floatValue:e}}let c=jw(i);return{...s,complexValue:[0,c]}}function kw(e,t){let n=Nw(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 Aw(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 jw(e){return Number(e)}function Mw(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 KC(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Nw(e,t,n){let r=Mw(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new KC(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function Pw(e,t){if(t(e)!==!1)for(let n of Fw(e))Pw(n,t)}function Fw(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 rw(e)}}const Iw=Symbol(`go-template-js.MISSING`);function Lw(e,t){if(e==null)return Iw;if(e instanceof Map)return e.has(t)?e.get(t):Iw;if(Array.isArray(e))return Iw;if(typeof e==`object`){let n=e;return t in n?n[t]:Iw}return Iw}function Rw(e,t){let n=e;for(let e of t){if(n===Iw)return Iw;n=Lw(n,e)}return n}function zw(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)=>zw(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)||!zw(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=>zw(e[n],t[n])):!1}return!1}const Bw=new WeakSet;function Vw(e){return Bw.add(e),e}function Hw(e){return Bw.has(e)}function Uw(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 Ww(e,t){return{eq:{fn:(e,...t)=>t.some(t=>qw(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!qw(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Jw(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Jw(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Jw(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Jw(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Yw(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Xw(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)=>tT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${tT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>uT(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>pT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>pT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>iT(tT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>sT(tT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>lT(tT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Uw(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Gw(){return{and:Vw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Uw(t))return t;return t}}),or:Vw({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Uw(t))return t;return t}})}}function Kw(e,t){return{...Ww(e,t),...Gw()}}function qw(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):zw(e,t)}function Jw(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 Yw(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Xw(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Zw(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 ${$w(t)}`);return e[t]}throw Error(`index: cannot index ${$w(e)}`)}function Zw(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 ${eT(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]=Zw(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 $w(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function eT(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 tT(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+=nT(a,t),r=o}return n}function nT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const rT={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function iT(e){return e.replace(/[\0"'&<>]/g,e=>rT[e]??e)}const aT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},oT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function sT(e){let t=``;for(let n of e){let e=aT[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!oT.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const cT=new TextEncoder;function lT(e){let t=``,n=cT.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 uT(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+=dT(l??``,u,d,n,r),o=c+1}return i}function dT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?fT(t,n):fT(t,nT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${eT(n)}=${nT(n,r)})`:fT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return fT(t,pT(n,r,i));case`q`:return fT(t,JSON.stringify(nT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${eT(n)}=${nT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return fT(t,Number(n).toFixed(i))}case`t`:return fT(t,Uw(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 fT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${eT(n)}=${nT(n,r)})`:typeof n==`bigint`?fT(t,n.toString(16)):fT(t,Math.trunc(n).toString(16));default:return`%!${e}(${eT(n)}=${nT(n,r)})`}}function fT(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 pT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>pT(e,t,n)).join(` `)}]`:e instanceof Map?mT([...e.entries()],t,n):hT(e)?mT(Object.entries(e),t,n):String(e)}function mT(e,t,n){let r=e=>pT(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 hT(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 gT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function _T(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function vT(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 yT(e,t,n){e.vars.set(t,n)}const bT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],xT=new Set([`default`,`zero`,`error`]);function ST(e){if(e===void 0)return`default`;if(xT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${CT(e)}`)}function CT(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 wT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${CT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${CT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${CT(e.right)}`);return{left:e.left,right:e.right}}}function TT(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function ET(e){let t=new Set(bT);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 ${bT.join(`, `)}`)}),TT(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 DT=Object.freeze({kind:`break`}),OT=Object.freeze({kind:`continue`}),kT={kind:`none`};let AT;(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{AT=(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 jT(e){let t=new Set,n=e=>{Pw(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 MT={kind:`dynamic`};function NT(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=eE(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:MT}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return MT;let t=e.cmds[0];if(t===void 0)return MT;let n=t.args[0];return n===void 0||n.type!==`Identifier`?MT:{kind:`call`,name:n.ident,args:t.args.slice(1).map(NT)}}default:return MT}}function PT(e){let t=[],n=e=>{Pw(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(NT);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 FT=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??UT,this.isT=e.isT??IT,this.missingKey=ST(e.missingKey),this.delims=wT(e.delims),this.funcs=ET({...Kw(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=bw(e,this.delims,t);return AT(n.source,e=>this.evalParsed(n,e),n.defines,jT(n),PT(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=gT(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 DT;case`Continue`:throw OT;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 qC(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:rw(e)}}evalIf(e,t,n){Uw(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(Uw(r)){let i=_T(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=ZT(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=_T(t,o);if(i.length===1)yT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;yT(a,e,r),yT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===OT)continue;throw e}}}catch(e){if(e===DT)return;throw e}}evalTemplateInvoke(e,t,n){let r=vw(n.defines,e.name);if(!r)throw new qC(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=_T(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=_T(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=vw(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 qC(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,kT);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)yT(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 qC(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new qC(`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 JC(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Hw(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){RT(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof XC?new XC(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof $C?new $C(t.message,r,{source:i.source}):t instanceof GC?t:new qC(`error calling ${e}: ${YT(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 eE(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 JC(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 qC(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Rw(e,t);if(i!==Iw)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=vT(t,i);if(!a.found)throw new qC(`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(pT(e,this.toString,this.isT)))}};const IT=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function LT(e){return new FT(e)}function RT(e,t,n,r,i,a=UT,o=HT,s=IT){let{argTypes:c,arity:l}=t,u=zT(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new YC(e,u,n.length,r,{source:i});let d=BT(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!VT(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new ZC(e,t+1,l,r,{source:i}):new XC(e,t+1,JT(c),XT(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(!GT(n[f],l))throw new XC(e,t+1,`${JT(`ordered`)} of the same kind as ${XT(n[f])}`,XT(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!KT(n[p],l))throw new XC(e,t+1,`${JT(`comparable`)} of the same kind as ${XT(n[p])}`,XT(l),r,{source:i})}}}function zT(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 BT(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 VT(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 hT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||hT(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||hT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||hT(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 WT(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function HT(e){return e}function UT(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 XC(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,XT(e),{line:0,column:0,offset:0})}function WT(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function GT(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function KT(e,t){let n=qT(e),r=qT(t);return n===`nil`||r===`nil`?!0:n===r}function qT(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 YT(e){return e instanceof Error?e.message:String(e)}function XT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function ZT(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?QT([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?QT(Object.entries(e)):[]}function QT(e){return[...e].sort((e,t)=>$T(e[0],t[0]))}function $T(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 eE(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 tE(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function nE(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 rE(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 iE(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=rE(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 aE(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=rE(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 oE(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 sE(e){return JSON.stringify(e)??`null`}function cE(){return{atoi:{fn:e=>tE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>iE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>aE(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>nE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>oE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>sE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const lE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function uE(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*lE[a],n=n.slice(e[0].length)}return t?-r:r}function dE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<lE.us?`${Math.floor(n)}ns`:n<lE.ms?fE(n,lE.us,3,`µs`):n<lE.s?fE(n,lE.ms,6,`ms`):pE(n),t?`-${r}`:r}function fE(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 pE(e){let t=Math.floor(e/lE.h);e-=t*lE.h;let n=Math.floor(e/lE.m);e-=n*lE.m;let r=Math.floor(e/lE.s),i=e-r*lE.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 mE(e){return e*lE.s}function hE(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 gE(e,t){let n=t().getTime()-hE(e).getTime();return dE(Math.round(n/1e3)*1e9)}const _E=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],vE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],yE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],bE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function xE(e){return e<10?`0${e}`:String(e)}function SE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function CE(e){return e<10?` ${e}`:String(e)}function wE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${xE(Math.floor(n/60))}${xE(n%60)}`}function TE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${xE(Math.floor(n/60))}:${xE(n%60)}`}function EE(e){return`${e>=0?`+`:`-`}${xE(Math.floor(Math.abs(e)/60))}`}function DE(e){return e===0?`Z`:wE(e)}function OE(e){return e===0?`Z`:TE(e)}function kE(e){return e===0?`Z`:EE(e)}function AE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const jE=[[`.000000000`,e=>`.${AE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=AE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${AE(e.ms,6,!1)}`],[`.999999`,e=>{let t=AE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${SE(e.ms)}`],[`.999`,e=>{let t=SE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>_E[e.month-1]??`January`],[`Monday`,e=>yE[e.weekday]??`Monday`],[`Z07:00`,e=>OE(e.offsetMinutes)],[`-07:00`,e=>TE(e.offsetMinutes)],[`Z0700`,e=>DE(e.offsetMinutes)],[`-0700`,e=>wE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>vE[e.month-1]??`Jan`],[`Mon`,e=>bE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>EE(e.offsetMinutes)],[`Z07`,e=>kE(e.offsetMinutes)],[`15`,e=>xE(e.hour)],[`01`,e=>xE(e.month)],[`02`,e=>xE(e.day)],[`_2`,e=>CE(e.day)],[`03`,e=>xE(e.hour12)],[`04`,e=>xE(e.minute)],[`05`,e=>xE(e.second)],[`06`,e=>xE(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 ME(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of jE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const NE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function PE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const FE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function IE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=PE(new Intl.DateTimeFormat(`en-US`,{...NE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=PE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=LE(PE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=FE.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 LE(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 RE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function zE(e,t){return ME(e,IE(hE(t),RE()))}function BE(e,t,n){return ME(e,IE(hE(t),n))}function VE(e,t){let n=hE(t),r=uE(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function HE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:dE(mE(t))}return typeof e==`bigint`?dE(mE(Number(e))):typeof e==`number`?dE(mE(e)):`0s`}const UE=36e11*24*365,WE=36e11*24*30,GE=36e11*24,KE=36e11,qE=6e10,JE=1e9;function YE(e){let t=uE(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>UE?`${Math.floor(n/UE)}y`:n>WE?`${Math.floor(n/WE)}mo`:n>GE?`${Math.floor(n/GE)}d`:n>KE?`${Math.floor(n/KE)}h`:n>qE?`${Math.floor(n/qE)}m`:n>JE?`${Math.floor(n/JE)}s`:`0s`}function XE(e){let t=IE(hE(e),RE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function ZE(e,t){let n=IE(hE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function QE(e){return e()}const $E=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],eD=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function tD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function nD(e,t,n){return[e.slice(t,t+n),t+n]}function rD(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 iD(e,t){for(let[n,r]of $E.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function aD(e,t){for(let[n,r]of eD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function oD(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 sD(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 cD(e,t){if(e[t]===` `){let[n,r]=rD(e,t+1,1,1);return[n,r]}return rD(e,t,1,2)}function lD(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]=rD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=rD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=rD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function uD(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]=rD(e,t+1,2,2);return[n*r*60,i]}return lD(e,t,n)}function dD(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 fD(e,t,n){let[r,i]=nD(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function pD(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=iD(t,n);return i.month=e,[r,i]}case`Monday`:return[oD(t,n),i];case`Jan`:{let[e,r]=aD(t,n);return i.month=e,[r,i]}case`Mon`:return[sD(t,n),i];case`2006`:{let[e,r]=rD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=rD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=rD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=rD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=cD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=rD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=rD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=rD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=rD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=rD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=rD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=rD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=rD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=rD(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[dD(t,n),i];case`-0700`:{let[e,r]=lD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=lD(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]=rD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=uD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=uD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=uD(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]=fD(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]=fD(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]=fD(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 mD=`.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 hD(e,t){let n=0,r=0,i=tD();for(;n<e.length;){let a=!1;for(let o of mD)if(e.startsWith(o,n)){let[e,s]=pD(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 gD(e,t){return hD(e,t)}function _D(e){return String(Math.floor(hE(e).getTime()/1e3))}function vD(e=()=>new Date){return{now:{fn:()=>QE(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>zE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>BE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>VE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>XE(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>ZE(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>HE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>YE(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>gD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>gE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>_D(e),argTypes:[`value`],arity:{kind:`exact`}}}}function yD(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 bD(...e){for(let t of e)if(!yD(t))return t}function xD(e,t){return yD(t)?e:t}function SD(e){return JSON.parse(e)}function CD(e,t,n){return Uw(n)?e:t}function wD(e){return JSON.stringify(e)??`null`}function TD(e){return JSON.stringify(e,null,2)??`null`}function ED(){return{default:{fn:(e,t)=>xD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>yD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>bD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>CD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>SD(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>wD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>TD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function DD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function OD(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 DD(...t)}function kD(e,t){return e[t]}function AD(e,t){return t in e}function jD(e){return Object.keys(e)}function MD(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 ND(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function PD(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 FD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function ID(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function LD(e,t,n){return e[t]=n,e}function RD(e,t){return delete e[t],e}function zD(e){return Object.values(e)}function BD(){return{dict:{fn:(...e)=>DD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>kD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>LD(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>RD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>jD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>zD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>ID(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>FD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>PD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>AD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>MD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>ND(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function VD(e){throw new $C(e)}function HD(){return{fail:{fn:e=>VD(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 UD(...e){for(let t of e)if(yD(t))return!1;return!0}function WD(...e){for(let t of e)if(!yD(t))return!0;return!1}function GD(e,t){return[...e,t]}function KD(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 qD(e){return e.filter(e=>!yD(e))}function JD(...e){let t=[];for(let n of e)t.push(...n);return t}const YD={line:0,column:0,offset:0};function XD(e,t,n,r){return new XC(e,t,n,r,YD)}function ZD(...e){if(e.length<3)throw XD(`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(!$D(t))throw XD(`dig`,e.length-1,`dict`,eO(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw XD(`dig`,e,`string`,eO(r[e]));return QD(t,n,r,e.length)}function QD(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(!$D(a))throw XD(`dig`,r-1,`dict at intermediate key`,eO(a));return QD(a,t,n.slice(1),r)}function $D(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function eO(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function tO(e){return e[0]}function nO(e,t){return t.some(t=>zw(t,e))}function rO(e){return e.slice(0,-1)}function iO(e){return e[e.length-1]}function aO(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function oO(...e){return e}function sO(e,t){return[t,...e]}function cO(e){return e.slice(1)}function lO(e){return[...e].reverse()}function uO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function dO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function fO(e){let t=[];for(let n of e)t.some(e=>zw(e,n))||t.push(n);return t}function pO(e,...t){return e.filter(e=>!t.some(t=>zw(t,e)))}function mO(){return{list:{fn:(...e)=>oO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>tO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>iO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>cO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>rO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>aO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>lO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>fO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>pO(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>nO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>qD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>uO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>JD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>KD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>sO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>GD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>dO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>GD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>oO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>ZD(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>UD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>WD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function hO(...e){return e.reduce((e,t)=>e+t,0)}function gO(e){return e+1}function _O(e){return e+1}function vO(...e){return e.reduce((e,t)=>e+t,0)}function yO(e){return Math.ceil(e)}function bO(e,t){return Math.trunc(e/t)}function xO(e,...t){return t.reduce((e,t)=>e/t,e)}function SO(e){return Math.floor(e)}function CO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function wO(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function TO(...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 DO(e,t){return e%t}function OO(...e){return e.reduce((e,t)=>e*t,1)}function kO(...e){return e.reduce((e,t)=>e*t,1)}function AO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function jO(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 MO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),jO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return jO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:jO(n,i+t,r).join(` `)}default:return``}}function NO(e,t){return e-t}function PO(e,...t){return t.reduce((e,t)=>e-t,e)}function FO(e){return jO(0,e,e<0?-1:1)}function IO(){return{add:{fn:(...e)=>hO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>NO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>OO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>bO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>DO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>TO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>CO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>SO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>yO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>AO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>vO(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>PO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>kO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>xO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>gO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>_O(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>wO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>EO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>CO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>MO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>FO(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>jO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function LO(e){return Array.from(e)}function RO(e,t){return e===``?LO(t):t.split(e)}function zO(e,t){let n=LO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function BO(e,t,n){let r=LO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const VO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},HO=/^[-_\s]$/,UO=/^\p{P}$/u,WO=/^\p{L}$/u,GO=/^\p{Lu}$/u,KO=/^\p{N}$/u;function qO(e){return e!==void 0&&HO.test(e)}function JO(e){return e!==void 0&&WO.test(e)}function YO(e){return e!==void 0&&GO.test(e)}function XO(e){return e!==void 0&&KO.test(e)}function ZO(e){return e!==void 0&&UO.test(e)}function QO(e,t){if(t>=e.length)return{word:{wt:VO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(qO(n)){for(;r<e.length&&qO(e[r]);)r++;return{word:{wt:VO.Connector,text:e.slice(t,r).join(``)},next:r}}if(ZO(n)){for(;r<e.length&&ZO(e[r]);)r++;return{word:{wt:VO.Punct,text:e.slice(t,r).join(``)},next:r}}if(YO(n)){if(r>=e.length)return{word:{wt:VO.UpperCase,text:n},next:r};if(YO(e[r])){let n=r;for(;n<e.length&&YO(e[n]);)n++;return n<e.length&&JO(e[n])?{word:{wt:VO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:VO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(JO(e[r])){let n=r+1;for(;n<e.length&&JO(e[n])&&!YO(e[n]);)n++;return{word:{wt:VO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:VO.UpperCase,text:n},next:r}}if(JO(n)){for(;r<e.length&&JO(e[r])&&!YO(e[r]);)r++;return{word:{wt:VO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(XO(n)){for(;r<e.length&&XO(e[r]);)r++;return{word:{wt:VO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!qO(e[r])&&!JO(e[r])&&!XO(e[r])&&!ZO(e[r]);)r++;return{word:{wt:VO.Other,text:e.slice(t,r).join(``)},next:r}}function $O(e,t,n){if(t.wt!==VO.UpperCase&&t.wt!==VO.Connector){e.push(t.text);return}for(let r of t.text)qO(r)?e.push(n):YO(r)?e.push(r.toLowerCase()):e.push(r)}function ek(e,t){if(e.length===0)return``;let n=LO(e),r=[],{word:i,next:a}=QO(n,0);for(;a<n.length;){i.wt!==VO.Connector&&$O(r,i,t);let e=i,o=i;if({word:i,next:a}=QO(n,a),e.wt===VO.Number){for(;i.wt===VO.Alphabet||i.wt===VO.Number;)$O(r,i,t),{word:i,next:a}=QO(n,a);i.wt!==VO.Invalid&&i.wt!==VO.Punct&&i.wt!==VO.Connector&&r.push(t);continue}if(e.wt===VO.Connector){$O(r,o,t);continue}if(e.wt===VO.Punct)continue;if(i.wt!==VO.Number){i.wt!==VO.Connector&&i.wt!==VO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=QO(n,a),i.wt!==VO.Alphabet){$O(r,s,t),i.wt!==VO.Connector&&i.wt!==VO.Punct&&r.push(t);continue}for(r.push(t),$O(r,s,t);i.wt===VO.Alphabet||i.wt===VO.Number;)$O(r,i,t),{word:i,next:a}=QO(n,a);i.wt!==VO.Invalid&&i.wt!==VO.Connector&&i.wt!==VO.Punct&&r.push(t)}return $O(r,i,t),r.join(``).toLowerCase()}function tk(e){if(e.length===0)return``;let t=LO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!qO(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++,qO(i)&&qO(e)){n.push(e);continue}qO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function nk(e){return tk(e)}function rk(...e){return e.join(` `)}function ik(e,t){return t.includes(e)}function ak(e,t){return t.startsWith(e)}function ok(e,t){return t.endsWith(e)}function sk(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
|
|
67
67
|
`).map(e=>n+e).join(`
|
|
68
|
-
`)}function
|
|
69
|
-
`,t)}function
|
|
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 zk(e,t,n){return Rk(e,t,n)}function Bk(){return{abbrev:{fn:(e,t)=>RO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>zO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>tk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>nk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>rk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>ik(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>ak(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>ok(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>sk(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>ck(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>uk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>dk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>fk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>pk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>mk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>hk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>gk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>_k(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>vk(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>yk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>bk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>xk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Sk(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>wk(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Tk(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>Ek(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>kk(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Ak(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>jk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>Mk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Nk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>Pk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Fk(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Ik(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Lk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>zk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Vk(e,t){let n=Hk(e),r=n.copy();return r.style=Pf(n.style,t),r}function Hk(e){if(!(e instanceof q))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Uk(e){return{fn:(t=>Vk(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Wk(e){return{fn:((t,n)=>Vk(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Gk(e,t){return new W({[e]:t})}function Kk(){let e={};for(let t of Ef)e[t]=Uk(Gk(t,!0)),e[`not_${t}`]=Uk(Gk(t,!1));for(let[t,n]of Object.entries(Of))e[t]=Uk(Gk(n,!0));return e}const qk={fn:((e,t)=>Vk(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},Jk={fn:((e,t)=>Vk(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function Yk(){return{fg:Wk(`color`),bg:Wk(`bgcolor`),...Kk(),link:Jk,style:qk}}function Xk(e,t){let n;try{n=hu(e.trim())}catch(n){throw n instanceof Zl?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 Zk(n,t,JSON.stringify(e))}function Zk(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 Qk(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function $k(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 eA=Qk([`string`,`int`],((e,t)=>rd(Xk(e,`darken`),t).hex)),tA=Qk([`string`,`int`],((e,t)=>rd(Xk(e,`lighten`),-t).hex)),nA={min:0,max:100,note:`0 = from, 100 = toward`},rA=Qk([`string`,`string`,`float`],((e,t,n)=>gu(Xk(e,`mix`),Xk(t,`mix`),$k(n,`mix`,`percentage`,nA)/100).hex)),iA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},aA=Qk([`string`],(e=>cd(Xk(e,`contrastOn`)).hex)),oA={depth:H.TRUECOLOR},sA=e=>Qk([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return ld(Xk(t,`readableOn`),Xk(n,`readableOn`),$k(r,`readableOn`,`ratio`,iA),i,void 0,a).hex})),cA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function lA(){let e={};for(let[t,n]of Object.entries(cA)){let r=t;e[n]=Qk([`string`,`float`],((e,t)=>{let i={...Fu,[r]:$k(t,n,`amount`)};return qu.fromRgba(Xk(e,n)).applyKey(i).toRgba().hex}))}return e}function uA(e=()=>oA){return{darken:eA,lighten:tA,mix:rA,contrastOn:aA,readableOn:sA(e),...lA()}}function dA(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:Zk(Zu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function fA(e){return{color:{fn:(t=>Zu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Dp(uf(n),dA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const pA=Pp.play(0);function mA(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 hA={...p_.loops,typewriter:e=>p_.transitions.typewriter(e).effect,scramble:e=>p_.transitions.scramble(e).effect,backspace:e=>p_.transitions.backspace(e).effect,scrambleOut:e=>p_.transitions.scrambleOut(e).effect};function gA(e){if(!Object.hasOwn(hA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(hA).map(e=>JSON.stringify(e)).join(`, `)}`);return hA[e]}function _A(e,t={}){let n=t.timeline??(()=>pA),r=(e,t,r)=>[Pp.run(n(),t),mf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=gp(a,o,i);return i.onHold?.(_p(s,o)),s.value},a=(e,t)=>Pp.run(Pp.play(e),t);return{frames:{fn:((...t)=>{let n=mA(`frame`,t,Hk).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return h_(...r(`frames`,new m_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=mA(`color`,e,e=>Xk(e,`stepped`));return t[i(`stepped`,xf(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,Ep(r,o,{seconds:e,ease:uf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Sf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=gA(t),s=Hk(i),c=s.plain,l=e();return h_(...r(`glyphs`,a(n,Gg(s,o({z:bh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function vA(e){return{...Yk(),...uA(e)}}new W({color:`red`,dim:!0});const yA=/^(?:(?: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,bA=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function xA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(yA);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(bA);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 SA(e){let t=e.match(bA);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 CA(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 wA(e){return e.toLocaleString()}function TA(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 EA(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 DA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],OA=DA.length;function kA(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*(OA-1));o+=DA[t]}return o}function AA(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 jA(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 MA=Zv(),NA=[...yy];function PA(){return{basename:{fn:e=>re(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>E(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>CA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(DC(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>EC(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>OC(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>MA,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>NA,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(jA(`sparkline`,[`width`],n),kA(AA(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>EA(e,TA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function FA(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 IA=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)=>FA(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function LA(){return{formatInteger:{fn:e=>wA(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>xA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>SA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let RA=null;function zA(e,t){if(RA!==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 RA=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{RA=null}}}function BA(e){if((0,Y._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(RA===null)throw Error(`the clock was read outside a draw (${e})`);return RA}const VA={now:()=>Ue(BA(`now`).at),frame:()=>BA(`frame`).frame,timeline:()=>BA(`timeline`).timeline};function HA(e,t){let{frames:n,stepped:r}=_A(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 UA=new Set([`now`,`ago`]);function WA(e,t){return Object.fromEntries(Object.entries(_D(e)).filter(([e])=>UA.has(e)===t))}const GA=WA(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),KA=[e=>WA(e.now,!0),e=>HA(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(HA(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),IA];function qA(e){return Object.assign({},...e.map(e=>e(VA)))}const JA=new Set(Object.keys(qA(KA)));function YA(e){return new Set([...JA,...Object.keys(qA(e))])}const XA={readableOn:sA},ZA=new Set(Object.keys(XA));function QA(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return IT({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...TD(),...Bk(),...pO(),...FO(),...sE(),...VD(),...zD(),...GA,...vA(r),...Object.fromEntries(Object.entries(XA).map(([e,t])=>[e,t(r)])),...qA([...KA,...e.clockFuncs??[]]),...PA(),...LA(),...n??{}}})}function $A(e){return ej(e,new Set(e.names()),``)}function ej(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!nj(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:rj(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return ej(e,t,a)}})}function tj(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 nj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function rj(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new kC(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var ij=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}};function aj(e){let t=T.basename(e),n=T.dirname(e);for(;;){let r=oj(n);if(r!==null)return{dir:r,name:t,leaf:n===T.dirname(e)};t=T.basename(n),n=T.dirname(n)}}function oj(e){try{return s.statSync(e).isDirectory()?s.realpathSync(e):null}catch{return null}}const sj=(e,t)=>k(t);function cj(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=jn(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=aj(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(oj))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=Yc(e.path);return[e.path,Zc(t)?Xc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function lj(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 uj(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 dj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([T.join(e,t)])},fj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),pj=(e,t)=>e.kind===`listening`&&e.handle===t,mj=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var hj=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??sj}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=mj(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=Yc(e.path);Zc(n)&&Xc(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,fj(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Xc(Yc(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(!pj(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,fj(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${z(i)} cause=${z(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(!pj(r,t))return;let i=n===T.basename(e.path)&&Xc(Yc(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,dj(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=uj(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=${z(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=${z(e)} cause=${z(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()}};function gj(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function _j(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var vj=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}};function yj(){return Y.observable.box(bj(`unread`),{deep:!1})}function bj(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function xj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,Y.compareStructural)(n,t)||((0,Y.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Sj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,Y.runInAction)(()=>e.reading.set({...n,why:t})):(0,Y.runInAction)(()=>e.reading.set(bj(t)))}function Cj(e,t){e.reading.get().kind===`pending`&&xj(e,t)}function wj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function Tj(e){return e.reading.get()}async function Ej(e){for(;;){let t=e();if(!wj(t))return t;await t.landed}}function Dj(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 Oj(e){return{current:()=>e}}const kj=()=>()=>{};var Aj=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 Oj(R(`${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:()=>Tj(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Sj(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:yj(),holders:0,flight:null,changed:!1,superseding:0,revisit:jj(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();Nj(()=>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{xj(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(),Cj(e,R(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function jj(e,t,n){if(e===null)return new Mj(n.holdReturned);let r=new vj(n.period,t);return{landed:t=>r.landed(gj(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var Mj=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 Nj(e){let t=e=>R(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const Pj=[`first`,`period`,`change`,`request`,`supersede`];var Fj=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 Lj(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(Pj.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Pj)e[n]+=t.refreshes[n]??0;return e}};const Ij={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Lj=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&&!Ij[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 Rj(e){return oe(`sha256`).update(JSON.stringify(zj(e))).digest(`hex`)}function zj(e){return Array.isArray(e)?e.map(zj):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,zj(t)])):e}const Bj=/\r\n|\r|\n/g,Vj=e=>I(e.replace(Bj,` `).trim());function Hj(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?R(`regex no-match`,`parse`):I(n.replace(Bj,` `))}}const Uj=e=>{try{return I(JSON.parse(e))}catch(e){return R(`JSON parse failed: ${e.message}`,`parse`)}},Wj=e=>Rj(e);function Gj(e){return ae.createHash(`sha256`).update(e).digest(`hex`)}const Kj=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function qj(e,t,n,r){return{where:Kj({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?I(i.stdout):R(`shell "${t}" ${Qe(i,` in ${n}`)}`,`read`)}}}function Jj(e,t,n){return{where:Kj({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await me(e,{encoding:`utf8`,signal:n});return I(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return R(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function Yj(e,t,n){switch(t.kind){case`shell`:return qj(e,t.command,t.cwd,n);case`file`:return Jj(t.path,t.readMode,n)}}function Xj(e){switch(e.kind){case`text`:return Vj;case`regex`:return Hj(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?L:Uj(e)}}function Zj(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?R(`${r.reason} in ${n}`,r.failedAt):r}var Qj=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=$j(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=$j(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 lj(`watch_file ${e}`,t.bound,il(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,Y.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 $j=e=>cj({named:[e],whole:[e]});var eM=class{byKind;watchMgr;faults=Y.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Pe,n=e.ledger??new Fj(t);this.watchMgr=new Qj(e.watchers??new hj({clock:e.clock}),e.fileEvents??$c);let r=r=>new Aj({name:`source.${r}`,scope:`daemon`,keyOf:Wj,fields:(e,t)=>`digest=${tn(Wj(e))} where=${z(Kj(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=Yj(e.launcher,t.read,n);return Zj(await r.read(),Xj(t.parse),r.where)},every:({refresh:e})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:(e,t)=>{if(e.refresh.kind!==`watch_file`)return kj();let n=Wj(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,Y.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,Y.runInAction)(()=>this.faults.delete(n))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let n=Wj(t),r=this.byKind[t.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 tM(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 nM(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const rM=`session.id`;function iM(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 aM={read:()=>Ao(`unread`),drawnAt:()=>{throw new kC(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},oM=e=>({kind:`found`,value:e});function sM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&jo(n))return n;if(typeof n!=`object`||!n)return oM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&jo(n)?n:oM(n)}function cM(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return R(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return R(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function lM(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`?EC(e):t===`number`?DC(e):OC(e)}function uM(e){return e===`number`?0:e===`boolean`?!1:``}var dM=class e{lastErrors=new Map;policyFaults=Y.observable.map(void 0,{deep:!1});cleanups=[];holds=new ij;identities=new Map;lanes=Y.observable.map(void 0,{deep:!1});inputs=Y.observable.box(aM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=QA({drawnAt:this.drawnAt});sourceNames=Y.observable.array([],{deep:!1});publishedNow=(0,Y.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,i=null,a={}){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.env=a,this.sessionState=r}view(){return new e(this.runs,new UC(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this,this.env)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,TC(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,R(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>cM(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 kC(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=lM(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},tM(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);(0,Y.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,Y.reaction)(()=>this.lanes.get(e)?.current(),e=>{e===void 0||e.kind===`pending`||i(e)},{fireImmediately:!0})),this.registerCachePolicy(e,n,n=>this.hold(e,{read:t,parse:iM(r),refresh:n}))}hold(e,t){this.identities.set(e,t);let{result:n}=this.holds.declare(()=>[...this.identities].map(([e,t])=>{let n=this.runs.declare(this.holds,t),r=this.lanes.get(e);return[e,r?.digest===n.digest?r:n]}));(0,Y.runInAction)(()=>{for(let[e,t]of n)this.lanes.set(e,t)})}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,Oo(t,n))}}documentPublisher(e,t){let n=t===void 0?Ao(`unread`):I(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()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,Y.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(ze(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate($A(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=lM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=AC(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`,e=>{let i=e(rM);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(rM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,Y.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.holds.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n({kind:`never`});break;case`ttl`:n({kind:`ttl`,durationMs:t.durationMs});break;case`watch_file`:n({kind:`watch_file`,path:t.path}),this.cleanups.push((0,Y.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?I(void 0):R(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return I(r.evaluate($A(this.store)).map(e=>e.plain).join(``))}catch(e){return AC(e)===void 0?R(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):Ao(`unread`)}},e=>n({kind:`key`,hash:Gj(e)}));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?I(e.map(e=>e.value).join(`,`)):Ao(`unread`)},e=>n({kind:`key`,hash:Gj(e)}));break}}onReads(e,t,n){let r,i=(0,Y.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n(t.value))},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return lM(this.defaultEmptyValue,t)}catch{return uM(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,Y.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 fM(e,t){let n=Ex[e],r=Mx(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 pM=Object.fromEntries([...Rx].map(([e,t])=>[t,fM(e,t)])),mM={subscribers:`number`,fps:`number`,shown:`boolean`},hM=Object.keys(mM),gM={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[rM]:{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:``},...pM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(ix.flatMap(e=>hM.map(t=>[lx(e,t),{kind:`input`,path:lx(e,t),type:mM[t],default:cx[t]}]))),[sx(`by`)]:{kind:`input`,path:sx(`by`),default:ox.by},[sx(`fps`)]:{kind:`input`,path:sx(`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:``}},_M={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 vM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(_M,t)?t:void 0}const yM=Object.fromEntries(ny.map(e=>[e,Rx.get(e)]));function bM(e){return ny.find(t=>yM[t]===e)}function xM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of $S(e??``,t).keys())r.add(n)};for(let t of Object.values(e.segments)){let e=t.partials===void 0?n:{...n,...t.partials};i(t.template,e),i(t.bg,e),i(t.fg,e),i(t.when,e);for(let n of Object.values(t.partials??{}))i(n,e)}for(let e of t)for(let t of zy(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(rM);for(let t of Object.values(e.actions)){r.add(rM);for(let[,e]of kS(t))i(e);let e=`set`in t?zx.get(t.set):void 0,n=`persist`in t?Rx.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function SM(e,t,n){let r=yC({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of xM(e,t,n.helpers)){if(vC(a,r))continue;let e=gM[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function CM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function wM(e){return e}function TM(e,t,n){return n===void 0?Mi+CM(e)+`.`+CM(t):EM(n)}function EM(e){return Mi+CM(e)}function DM(e,t){return e+`.`+t}function OM(e){return Ni+e}const kM=[`closeOnPick`,`paged`,`key`,`distribution`],AM=e=>kM.includes(e),jM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${av.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function MM(e){for(let t of Object.keys(e))if(!AM(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${jM}`);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&&!ov(r))throw Error(`{{ menu }} option "distribution" must be one of: ${av.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:cv(r)}}const NM=e=>`from`in e?e.from:e.themes;function PM(e,t,n){return e===`bool`?jy(t)!==null:`min`in e?My(t,e)!==null:wS(NM(e),n).members.includes(t)}function FM(e,t){if(e===`bool`)return ky.join(` or `);if(!(`min`in e)){let n=NM(e),{members:r}=wS(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 IM(e){return{label:e.label,domain:LM(e.domain)}}function LM(e){return e===`theme`?{themes:xS}:e===`bool`||`min`in e?e:{from:e}}function RM(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:[...ky]}},variables:{}};if(`from`in o)return zM(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 zM(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 zM(e,t,n,r,i){let a={variable:n,key:n,member:t},o=DM(n,t),s=`${t}.open`,c=OM(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,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const BM=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],VM=Object.fromEntries(BM.map(e=>[e.member,e.label])),HM={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},UM=Object.keys(HM),WM=Bx(e=>Px[e].place),GM=e=>Object.hasOwn(HM,e),KM=(e,t)=>e===t||GM(e)&&KM(WM[HM[e].beside],t),qM=e=>GM(e)?`${qM(WM[HM[e].beside])} › ${HM[e].trigger}`:e===`door`?`first line`:VM[e],JM=e=>qM(WM[e]),YM=()=>[`door`,...BM.map(e=>e.member)].flatMap(e=>[e,...UM.filter(t=>KM(t,e))]).map(e=>({path:qM(e),names:Fx.filter(t=>WM[t]===e)})).filter(({names:e})=>e.length>0),XM=e=>{let{setting:t,on:n,inTmux:r}=rx[e].switch;return`${rx[e].label} is off — turn it on in the settings menu's ${JM(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},ZM=Object.fromEntries(Object.entries(Ex).map(([e,t])=>[e,t.spec]));function QM(e){return $M(Ex[e])}function $M(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function eN(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:J(e.source,[...n.split(`.`),r])})}}}function tN(e){return eN(`${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 nN(e){return eN(`${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 rN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&ry(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:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const iN={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 ${JM(`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."},aN={noun:`globals key`,fields:ZM,removed:iN},oN={preset:tN(`a preset`),menuGlyph:nN(`a preset`)},sN={noun:`preset globals key`,fields:{...ZM,...oN},removed:iN};function cN(e){return vN(e)&&!(e in oN)}const lN=`is decided later than any rule could be settled`,uN={noun:`editGlobals key`,removed:iN,fields:{...ZM,preset:tN(`the editGlobals fragment`),menuGlyph:nN(`the editGlobals fragment`),palette:rN(ZM.palette,`the editGlobals fragment`,lN),style:rN(ZM.style,`the editGlobals fragment`,lN),effect:rN(ZM.effect,`the editGlobals fragment`,lN)}},dN={noun:`theme default key`,fields:{...Object.fromEntries(kx.map(e=>[e,ZM[e]])),style:rN(ZM.style,`a theme's default`,`is the look that theme wears by name`)}};function fN(e,t){if(!Db(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Ob(t)}`,line:J(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${Jv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=Ab(e,dN,t,i);a!==null&&(n[r]=a)}return n}function pN(e,t,n){return n===void 0?{}:Ab(e,aN,t,n)??{}}function mN(e,t,n){return Ab(e,sN,t,n)??{}}function hN(){return Zb(sN)}function gN(e,t,n){return Ab(e,uN,t,n)??{}}const _N=new Set(Object.keys(ZM));function vN(e){return _N.has(e)}function yN(e){return Object.hasOwn(iN,e)?iN[e]:void 0}function bN(){return[..._N]}const xN=new Map(Object.entries(Ex).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function SN(e){let t=new Map;for(let[n,r]of xN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const CN=/^segments\.([^.]+)\.palette$/,wN=/^presets\.(.+)\.root$/,TN=/^presets\.(.+)\.globals\.([^.]+)$/,EN=/^themeDefaults\.(.+)\.([^.]+)$/;function DN(e){return`presets.${e}.root`}function ON(e,t){return`themeDefaults.${e}.${t}`}const kN=e=>kx.includes(e);function AN(e,t){return`presets.${e}.globals.${t}`}function jN(e){if(vN(e))return{scope:`globals`,field:e};let t=CN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=TN.exec(e);if(n&&cN(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=EN.exec(e);if(r&&kN(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=wN.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function MN(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 NN=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],PN=[...NN,`other`],FN={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},IN=IT({fromString:e=>e});function LN(e){let t=CM(e);return Fi.find(e=>t.startsWith(CM(e)))}function RN(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:J(e.source,[`root`])})}function zN(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=IS(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:J(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=IS(i);a===void 0||n.has(r)||e.issues.push({path:`segments.${r}.vars.${t}`,message:`segment "${r}"'s var "${t}" is named "${i}", in "${a}", the namespace plugins own — rename the var or the segment`,line:J(e.source,[`segments`,r,`vars`,t])})}}const BN=`edit.mode`,VN=`edit.configure`,HN=`edit.toggle`,UN=`arrange`,WN=`${Pi}draft.`;function GN(e,t){return`${e}:${t}`}const KN={variable:BN,key:BN,member:UN},qN=Ci(KN);function JN(e){try{return IN.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function YN(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`&&JN(t))return!0}return!1}function XN(e,t){if(RN(e,t,Pi,`edit mode`),!YN(t))return;let{variables:n,actions:r}=ZN();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function ZN(){return{variables:{[BN]:{...Oi(BN,P),within:[zi]},[VN]:{...Oi(VN,P),within:[KN]}},actions:{[HN]:ki(BN,UN),"edit.unconfigure":{set:VN,to:P}}}}function QN(e,t,n,r){let i={variable:e,key:e,member:_i};return r.variables[e]={...Oi(e,P),...n.length>0&&{within:n}},r.actions[e]=ki(e,_i),r.segments[e]={template:Ti(e,`(?)`,`✕`),...$N(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 $N(e){let[t,...n]=e;return t===void 0?{}:{when:Ci(t,...n)}}const eP=`none`;function tP(e){return Zu(e,`background`)}var nP=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function rP(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=iP(n,i),l=c!==eP,u=l?c===void 0?o:aP(a,c,`bg`):tP(a);e.bg=u;let d=iP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:wv(a,e,t))(u):void 0:aP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function iP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function aP(e,t,n){try{return Zu(e,t)}catch(e){throw e instanceof Xu?new nP(t,n,e.message):e}}const oP=`🔧`,sP={help:[`-h`,`--help`],version:[`-V`,`--version`]},cP=[...new Set(Object.values(rx).map(e=>JM(e.switch.setting)))].join(` or `),lP=Math.max(...Object.values(Px).map(e=>e.configKey.length))+2,uP=[`✚ inserts`,`✖ removes`,`${oP} configures`,`↺ resets layout`],dP={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`]},fP=`
|
|
68
|
+
`)}function ck(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 lk(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw XD(`join`,2,`list of strings/primitives`,`list element of type ${uk(e)}`);n.push(String(e))}return n.join(e)}function uk(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function dk(e){return ek(e,`-`)}function fk(e){return e.toLowerCase()}function pk(e,t){return`\n${sk(e,t)}`}function mk(e){return e.replace(/\s+/g,``)}function hk(e,t,n){return n===1?e:t}function gk(...e){return e.map(e=>`"${e}"`).join(` `)}function _k(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function vk(e,t){return t.repeat(Math.max(0,e))}function yk(e,t,n){return RO(e,n).join(t)}function bk(e){return ek(e,`_`)}function xk(e,t){let n=RO(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Sk(e,t){return RO(e,t)}function Ck(e,t,n){let r=wk(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function wk(e,t,n){if(n===0)return[];let r=RO(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 Tk(...e){return e.map(e=>`'${e}'`).join(` `)}function Ek(e,t,n){let r=LO(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 Dk(e){let t=``;for(let n of e)Ok(n)?t+=n.toLowerCase():kk(n)?t+=n.toUpperCase():t+=n;return t}function Ok(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function kk(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Ak(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function jk(e){return e.trim()}function Mk(e,t){if(e.length===0)return t;let n=new Set(LO(e)),r=LO(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 Nk(e,t){return t.startsWith(e)?t.slice(e.length):t}function Pk(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function Fk(e,t){let n=LO(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 Ik(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function Lk(e){return e.toUpperCase()}function Rk(e,t){return zk(e,`
|
|
69
|
+
`,t)}function zk(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 Bk(e,t,n){return zk(e,t,n)}function Vk(){return{abbrev:{fn:(e,t)=>zO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>BO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>nk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>rk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ik(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>ak(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>ok(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>sk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>ck(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>lk(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>dk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>fk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>pk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>mk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>hk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>gk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>_k(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>vk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>yk(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>bk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>xk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Sk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Ck(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>Tk(...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=>Dk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Ak(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>jk(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Mk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>Nk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Pk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>Fk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Ik(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Lk(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Rk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>Bk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Hk(e,t){let n=Uk(e),r=n.copy();return r.style=Pf(n.style,t),r}function Uk(e){if(!(e instanceof q))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Wk(e){return{fn:(t=>Hk(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Gk(e){return{fn:((t,n)=>Hk(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Kk(e,t){return new W({[e]:t})}function qk(){let e={};for(let t of Ef)e[t]=Wk(Kk(t,!0)),e[`not_${t}`]=Wk(Kk(t,!1));for(let[t,n]of Object.entries(Of))e[t]=Wk(Kk(n,!0));return e}const Jk={fn:((e,t)=>Hk(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},Yk={fn:((e,t)=>Hk(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function Xk(){return{fg:Gk(`color`),bg:Gk(`bgcolor`),...qk(),link:Yk,style:Jk}}function Zk(e,t){let n;try{n=hu(e.trim())}catch(n){throw n instanceof Zl?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 Qk(n,t,JSON.stringify(e))}function Qk(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 $k(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function eA(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 tA=$k([`string`,`int`],((e,t)=>rd(Zk(e,`darken`),t).hex)),nA=$k([`string`,`int`],((e,t)=>rd(Zk(e,`lighten`),-t).hex)),rA={min:0,max:100,note:`0 = from, 100 = toward`},iA=$k([`string`,`string`,`float`],((e,t,n)=>gu(Zk(e,`mix`),Zk(t,`mix`),eA(n,`mix`,`percentage`,rA)/100).hex)),aA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},oA=$k([`string`],(e=>cd(Zk(e,`contrastOn`)).hex)),sA={depth:H.TRUECOLOR},cA=e=>$k([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return ld(Zk(t,`readableOn`),Zk(n,`readableOn`),eA(r,`readableOn`,`ratio`,aA),i,void 0,a).hex})),lA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function uA(){let e={};for(let[t,n]of Object.entries(lA)){let r=t;e[n]=$k([`string`,`float`],((e,t)=>{let i={...Fu,[r]:eA(t,n,`amount`)};return qu.fromRgba(Zk(e,n)).applyKey(i).toRgba().hex}))}return e}function dA(e=()=>sA){return{darken:tA,lighten:nA,mix:iA,contrastOn:oA,readableOn:cA(e),...uA()}}function fA(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:Qk(Zu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function pA(e){return{color:{fn:(t=>Zu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Dp(uf(n),fA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const mA=Pp.play(0);function hA(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 gA={...p_.loops,typewriter:e=>p_.transitions.typewriter(e).effect,scramble:e=>p_.transitions.scramble(e).effect,backspace:e=>p_.transitions.backspace(e).effect,scrambleOut:e=>p_.transitions.scrambleOut(e).effect};function _A(e){if(!Object.hasOwn(gA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(gA).map(e=>JSON.stringify(e)).join(`, `)}`);return gA[e]}function vA(e,t={}){let n=t.timeline??(()=>mA),r=(e,t,r)=>[Pp.run(n(),t),mf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=gp(a,o,i);return i.onHold?.(_p(s,o)),s.value},a=(e,t)=>Pp.run(Pp.play(e),t);return{frames:{fn:((...t)=>{let n=hA(`frame`,t,Uk).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return h_(...r(`frames`,new m_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=hA(`color`,e,e=>Zk(e,`stepped`));return t[i(`stepped`,xf(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,Ep(r,o,{seconds:e,ease:uf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Sf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=_A(t),s=Uk(i),c=s.plain,l=e();return h_(...r(`glyphs`,a(n,Gg(s,o({z:bh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function yA(e){return{...Xk(),...dA(e)}}new W({color:`red`,dim:!0});const bA=/^(?:(?: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,xA=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function SA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(bA);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(xA);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 CA(e){let t=e.match(xA);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 wA(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 TA(e){return e.toLocaleString()}function EA(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 DA(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 OA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],kA=OA.length;function AA(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*(kA-1));o+=OA[t]}return o}function jA(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 MA(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 NA=Zv(),PA=[...yy];function FA(){return{basename:{fn:e=>re(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>E(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>wA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(OC(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>DC(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>kC(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>NA,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>PA,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(MA(`sparkline`,[`width`],n),AA(jA(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>DA(e,EA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function IA(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 LA=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)=>IA(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function RA(){return{formatInteger:{fn:e=>TA(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>SA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>CA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let zA=null;function BA(e,t){if(zA!==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 zA=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{zA=null}}}function VA(e){if((0,Y._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(zA===null)throw Error(`the clock was read outside a draw (${e})`);return zA}const HA={now:()=>Ue(VA(`now`).at),frame:()=>VA(`frame`).frame,timeline:()=>VA(`timeline`).timeline};function UA(e,t){let{frames:n,stepped:r}=vA(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 WA=new Set([`now`,`ago`]);function GA(e,t){return Object.fromEntries(Object.entries(vD(e)).filter(([e])=>WA.has(e)===t))}const KA=GA(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),qA=[e=>GA(e.now,!0),e=>UA(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(UA(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),LA];function JA(e){return Object.assign({},...e.map(e=>e(HA)))}const YA=new Set(Object.keys(JA(qA)));function XA(e){return new Set([...YA,...Object.keys(JA(e))])}const ZA={readableOn:cA},QA=new Set(Object.keys(ZA));function $A(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return LT({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...ED(),...Vk(),...mO(),...IO(),...cE(),...HD(),...BD(),...KA,...yA(r),...Object.fromEntries(Object.entries(ZA).map(([e,t])=>[e,t(r)])),...JA([...qA,...e.clockFuncs??[]]),...FA(),...RA(),...n??{}}})}function ej(e){return tj(e,new Set(e.names()),``)}function tj(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!rj(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:ij(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return tj(e,t,a)}})}function nj(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 rj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function ij(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new AC(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var aj=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}};function oj(e){let t=T.basename(e),n=T.dirname(e);for(;;){let r=sj(n);if(r!==null)return{dir:r,name:t,leaf:n===T.dirname(e)};t=T.basename(n),n=T.dirname(n)}}function sj(e){try{return s.statSync(e).isDirectory()?s.realpathSync(e):null}catch{return null}}const cj=(e,t)=>k(t);function lj(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=jn(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=oj(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(sj))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=Yc(e.path);return[e.path,Zc(t)?Xc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function uj(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 dj(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 fj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([T.join(e,t)])},pj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),mj=(e,t)=>e.kind===`listening`&&e.handle===t,hj=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var gj=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??cj}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=hj(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=Yc(e.path);Zc(n)&&Xc(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,pj(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Xc(Yc(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(!mj(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,pj(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${z(i)} cause=${z(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(!mj(r,t))return;let i=n===T.basename(e.path)&&Xc(Yc(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,fj(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=dj(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=${z(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=${z(e)} cause=${z(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()}};function _j(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function vj(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var yj=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}};function bj(){return Y.observable.box(xj(`unread`),{deep:!1})}function xj(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function Sj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,Y.compareStructural)(n,t)||((0,Y.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Cj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,Y.runInAction)(()=>e.reading.set({...n,why:t})):(0,Y.runInAction)(()=>e.reading.set(xj(t)))}function wj(e,t){e.reading.get().kind===`pending`&&Sj(e,t)}function Tj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function Ej(e){return e.reading.get()}async function Dj(e){for(;;){let t=e();if(!Tj(t))return t;await t.landed}}function Oj(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 kj(e){return{current:()=>e}}const Aj=()=>()=>{};var jj=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 kj(R(`${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:()=>Ej(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Cj(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:bj(),holders:0,flight:null,changed:!1,superseding:0,revisit:Mj(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();Pj(()=>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{Sj(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(),wj(e,R(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function Mj(e,t,n){if(e===null)return new Nj(n.holdReturned);let r=new yj(n.period,t);return{landed:t=>r.landed(_j(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var Nj=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 Pj(e){let t=e=>R(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const Fj=[`first`,`period`,`change`,`request`,`supersede`];var Ij=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 Rj(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(Fj.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Fj)e[n]+=t.refreshes[n]??0;return e}};const Lj={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Rj=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&&!Lj[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 zj(e){return oe(`sha256`).update(JSON.stringify(Bj(e))).digest(`hex`)}function Bj(e){return Array.isArray(e)?e.map(Bj):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,Bj(t)])):e}const Vj=/\r\n|\r|\n/g,Hj=e=>I(e.replace(Vj,` `).trim());function Uj(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?R(`regex no-match`,`parse`):I(n.replace(Vj,` `))}}const Wj=e=>{try{return I(JSON.parse(e))}catch(e){return R(`JSON parse failed: ${e.message}`,`parse`)}},Gj=e=>zj(e);function Kj(e){return ae.createHash(`sha256`).update(e).digest(`hex`)}const qj=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function Jj(e,t,n,r){return{where:qj({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?I(i.stdout):R(`shell "${t}" ${Qe(i,` in ${n}`)}`,`read`)}}}function Yj(e,t,n){return{where:qj({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await me(e,{encoding:`utf8`,signal:n});return I(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return R(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function Xj(e,t,n){switch(t.kind){case`shell`:return Jj(e,t.command,t.cwd,n);case`file`:return Yj(t.path,t.readMode,n)}}function Zj(e){switch(e.kind){case`text`:return Hj;case`regex`:return Uj(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?L:Wj(e)}}function Qj(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?R(`${r.reason} in ${n}`,r.failedAt):r}var $j=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=eM(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=eM(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 uj(`watch_file ${e}`,t.bound,il(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,Y.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 eM=e=>lj({named:[e],whole:[e]});var tM=class{byKind;watchMgr;faults=Y.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Pe,n=e.ledger??new Ij(t);this.watchMgr=new $j(e.watchers??new gj({clock:e.clock}),e.fileEvents??$c);let r=r=>new jj({name:`source.${r}`,scope:`daemon`,keyOf:Gj,fields:(e,t)=>`digest=${tn(Gj(e))} where=${z(qj(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=Xj(e.launcher,t.read,n);return Qj(await r.read(),Zj(t.parse),r.where)},every:({refresh:e})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:(e,t)=>{if(e.refresh.kind!==`watch_file`)return Aj();let n=Gj(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,Y.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,Y.runInAction)(()=>this.faults.delete(n))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let n=Gj(t),r=this.byKind[t.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 nM(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 rM(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const iM=`session.id`;function aM(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 oM={read:()=>Ao(`unread`),drawnAt:()=>{throw new AC(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},sM=e=>({kind:`found`,value:e});function cM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&jo(n))return n;if(typeof n!=`object`||!n)return sM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&jo(n)?n:sM(n)}function lM(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return R(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return R(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function uM(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`?DC(e):t===`number`?OC(e):kC(e)}function dM(e){return e===`number`?0:e===`boolean`?!1:``}var fM=class e{lastErrors=new Map;policyFaults=Y.observable.map(void 0,{deep:!1});cleanups=[];holds=new aj;identities=new Map;lanes=Y.observable.map(void 0,{deep:!1});inputs=Y.observable.box(oM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=$A({drawnAt:this.drawnAt});sourceNames=Y.observable.array([],{deep:!1});publishedNow=(0,Y.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,i=null){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.sessionState=r}view(){return new e(this.runs,new WC(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,EC(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,R(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>lM(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 AC(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=uM(a,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareShell(e,t,n){this.declareSource(e,{kind:`shell`,command:t,cwd:n.cwd},nM(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);(0,Y.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,Y.reaction)(()=>this.lanes.get(e)?.current(),e=>{e===void 0||e.kind===`pending`||i(e)},{fireImmediately:!0})),this.registerCachePolicy(e,n,n=>this.hold(e,{read:t,parse:aM(r),refresh:n}))}hold(e,t){this.identities.set(e,t);let{result:n}=this.holds.declare(()=>[...this.identities].map(([e,t])=>{let n=this.runs.declare(this.holds,t),r=this.lanes.get(e);return[e,r?.digest===n.digest?r:n]}));(0,Y.runInAction)(()=>{for(let[e,t]of n)this.lanes.set(e,t)})}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,Oo(t,n))}}documentPublisher(e,t){let n=t===void 0?Ao(`unread`):I(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()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,Y.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(ze(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(ej(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=uM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=jC(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`,e=>{let i=e(iM);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(iM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,Y.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.holds.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n({kind:`never`});break;case`ttl`:n({kind:`ttl`,durationMs:t.durationMs});break;case`watch_file`:n({kind:`watch_file`,path:t.path}),this.cleanups.push((0,Y.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?I(void 0):R(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return I(r.evaluate(ej(this.store)).map(e=>e.plain).join(``))}catch(e){return jC(e)===void 0?R(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):Ao(`unread`)}},e=>n({kind:`key`,hash:Kj(e)}));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?I(e.map(e=>e.value).join(`,`)):Ao(`unread`)},e=>n({kind:`key`,hash:Kj(e)}));break}}onReads(e,t,n){let r,i=(0,Y.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n(t.value))},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return uM(this.defaultEmptyValue,t)}catch{return dM(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,Y.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 pM(e,t){let n=Dx[e],r=Nx(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 mM=Object.fromEntries([...zx].map(([e,t])=>[t,pM(e,t)])),hM={subscribers:`number`,fps:`number`,shown:`boolean`},gM=Object.keys(hM),_M={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[iM]:{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:``},...mM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(ix.flatMap(e=>gM.map(t=>[lx(e,t),{kind:`input`,path:lx(e,t),type:hM[t],default:cx[t]}]))),[sx(`by`)]:{kind:`input`,path:sx(`by`),default:ox.by},[sx(`fps`)]:{kind:`input`,path:sx(`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:``}},vM={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 yM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(vM,t)?t:void 0}const bM=Object.fromEntries(ny.map(e=>[e,zx.get(e)]));function xM(e){return ny.find(t=>bM[t]===e)}function SM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of eC(e??``,t).keys())r.add(n)};for(let t of Object.values(e.segments)){let e=t.partials===void 0?n:{...n,...t.partials};i(t.template,e),i(t.bg,e),i(t.fg,e),i(t.when,e);for(let n of Object.values(t.partials??{}))i(n,e)}for(let e of t)for(let t of zy(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(iM);for(let t of Object.values(e.actions)){r.add(iM);for(let[,e]of AS(t))i(e);let e=`set`in t?Bx.get(t.set):void 0,n=`persist`in t?zx.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function CM(e,t,n){let r=bC({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of SM(e,t,n.helpers)){if(yC(a,r))continue;let e=_M[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function wM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function TM(e){return e}function EM(e,t,n){return n===void 0?Mi+wM(e)+`.`+wM(t):DM(n)}function DM(e){return Mi+wM(e)}function OM(e,t){return e+`.`+t}function kM(e){return Ni+e}const AM=[`closeOnPick`,`paged`,`key`,`distribution`],jM=e=>AM.includes(e),MM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${av.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function NM(e){for(let t of Object.keys(e))if(!jM(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${MM}`);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&&!ov(r))throw Error(`{{ menu }} option "distribution" must be one of: ${av.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:cv(r)}}const PM=e=>`from`in e?e.from:e.themes;function FM(e,t,n){return e===`bool`?jy(t)!==null:`min`in e?My(t,e)!==null:TS(PM(e),n).members.includes(t)}function IM(e,t){if(e===`bool`)return ky.join(` or `);if(!(`min`in e)){let n=PM(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 LM(e){return{label:e.label,domain:RM(e.domain)}}function RM(e){return e===`theme`?{themes:SS}:e===`bool`||`min`in e?e:{from:e}}function zM(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:[...ky]}},variables:{}};if(`from`in o)return BM(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 BM(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 BM(e,t,n,r,i){let a={variable:n,key:n,member:t},o=OM(n,t),s=`${t}.open`,c=kM(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,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const VM=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],HM=Object.fromEntries(VM.map(e=>[e.member,e.label])),UM={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},WM=Object.keys(UM),GM=Vx(e=>Fx[e].place),KM=e=>Object.hasOwn(UM,e),qM=(e,t)=>e===t||KM(e)&&qM(GM[UM[e].beside],t),JM=e=>KM(e)?`${JM(GM[UM[e].beside])} › ${UM[e].trigger}`:e===`door`?`first line`:HM[e],YM=e=>JM(GM[e]),XM=()=>[`door`,...VM.map(e=>e.member)].flatMap(e=>[e,...WM.filter(t=>qM(t,e))]).map(e=>({path:JM(e),names:Ix.filter(t=>GM[t]===e)})).filter(({names:e})=>e.length>0),ZM=e=>{let{setting:t,on:n,inTmux:r}=rx[e].switch;return`${rx[e].label} is off — turn it on in the settings menu's ${YM(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},QM=Object.fromEntries(Object.entries(Dx).map(([e,t])=>[e,t.spec]));function $M(e){return eN(Dx[e])}function eN(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function tN(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:J(e.source,[...n.split(`.`),r])})}}}function nN(e){return tN(`${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 rN(e){return tN(`${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 iN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&ry(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:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const aN={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 ${YM(`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."},oN={noun:`globals key`,fields:QM,removed:aN},sN={preset:nN(`a preset`),menuGlyph:rN(`a preset`)},cN={noun:`preset globals key`,fields:{...QM,...sN},removed:aN};function lN(e){return yN(e)&&!(e in sN)}const uN=`is decided later than any rule could be settled`,dN={noun:`editGlobals key`,removed:aN,fields:{...QM,preset:nN(`the editGlobals fragment`),menuGlyph:rN(`the editGlobals fragment`),palette:iN(QM.palette,`the editGlobals fragment`,uN),style:iN(QM.style,`the editGlobals fragment`,uN),effect:iN(QM.effect,`the editGlobals fragment`,uN)}},fN={noun:`theme default key`,fields:{...Object.fromEntries(Ax.map(e=>[e,QM[e]])),style:iN(QM.style,`a theme's default`,`is the look that theme wears by name`)}};function pN(e,t){if(!Db(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Ob(t)}`,line:J(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${Jv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=Ab(e,fN,t,i);a!==null&&(n[r]=a)}return n}function mN(e,t,n){return n===void 0?{}:Ab(e,oN,t,n)??{}}function hN(e,t,n){return Ab(e,cN,t,n)??{}}function gN(){return Zb(cN)}function _N(e,t,n){return Ab(e,dN,t,n)??{}}const vN=new Set(Object.keys(QM));function yN(e){return vN.has(e)}function bN(e){return Object.hasOwn(aN,e)?aN[e]:void 0}function xN(){return[...vN]}const SN=new Map(Object.entries(Dx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function CN(e){let t=new Map;for(let[n,r]of SN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const wN=/^segments\.([^.]+)\.palette$/,TN=/^presets\.(.+)\.root$/,EN=/^presets\.(.+)\.globals\.([^.]+)$/,DN=/^themeDefaults\.(.+)\.([^.]+)$/;function ON(e){return`presets.${e}.root`}function kN(e,t){return`themeDefaults.${e}.${t}`}const AN=e=>Ax.includes(e);function jN(e,t){return`presets.${e}.globals.${t}`}function MN(e){if(yN(e))return{scope:`globals`,field:e};let t=wN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=EN.exec(e);if(n&&lN(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=DN.exec(e);if(r&&AN(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=TN.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function NN(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 PN=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],FN=[...PN,`other`],IN={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},LN=LT({fromString:e=>e});function RN(e){let t=wM(e);return Fi.find(e=>t.startsWith(wM(e)))}function zN(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:J(e.source,[`root`])})}function BN(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=LS(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:J(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=LS(i);a===void 0||n.has(r)||e.issues.push({path:`segments.${r}.vars.${t}`,message:`segment "${r}"'s var "${t}" is named "${i}", in "${a}", the namespace plugins own — rename the var or the segment`,line:J(e.source,[`segments`,r,`vars`,t])})}}const VN=`edit.mode`,HN=`edit.configure`,UN=`edit.toggle`,WN=`arrange`,GN=`${Pi}draft.`;function KN(e,t){return`${e}:${t}`}const qN={variable:VN,key:VN,member:WN},JN=Ci(qN);function YN(e){try{return LN.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function XN(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`&&YN(t))return!0}return!1}function ZN(e,t){if(zN(e,t,Pi,`edit mode`),!XN(t))return;let{variables:n,actions:r}=QN();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function QN(){return{variables:{[VN]:{...Oi(VN,P),within:[zi]},[HN]:{...Oi(HN,P),within:[qN]}},actions:{[UN]:ki(VN,WN),"edit.unconfigure":{set:HN,to:P}}}}function $N(e,t,n,r){let i={variable:e,key:e,member:_i};return r.variables[e]={...Oi(e,P),...n.length>0&&{within:n}},r.actions[e]=ki(e,_i),r.segments[e]={template:Ti(e,`(?)`,`✕`),...eP(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 eP(e){let[t,...n]=e;return t===void 0?{}:{when:Ci(t,...n)}}const tP=`none`;function nP(e){return Zu(e,`background`)}var rP=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function iP(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=aP(n,i),l=c!==tP,u=l?c===void 0?o:oP(a,c,`bg`):nP(a);e.bg=u;let d=aP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:wv(a,e,t))(u):void 0:oP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function aP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function oP(e,t,n){try{return Zu(e,t)}catch(e){throw e instanceof Xu?new rP(t,n,e.message):e}}const sP=`🔧`,cP={help:[`-h`,`--help`],version:[`-V`,`--version`]},lP=[...new Set(Object.values(rx).map(e=>YM(e.switch.setting)))].join(` or `),uP=Math.max(...Object.values(Fx).map(e=>e.configKey.length))+2,dP=[`✚ inserts`,`✖ removes`,`${sP} configures`,`↺ resets layout`],fP={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`]},pP=`
|
|
71
71
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
72
72
|
|
|
73
73
|
Usage: cc-candybar [options]
|
|
74
74
|
|
|
75
75
|
Standalone Commands:
|
|
76
|
-
${
|
|
77
|
-
${
|
|
76
|
+
${cP.help.join(`, `).padEnd(25)}Show this help
|
|
77
|
+
${cP.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
|
|
78
78
|
|
|
79
79
|
Debugging:
|
|
80
80
|
CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
|
|
@@ -91,21 +91,21 @@ 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, ${VM.map(e=>e.label).join(`, `)};
|
|
95
|
+
${HM.session} holds quick actions and commands, ${HM.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
|
+
${XM().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${Fx[e].configKey.padEnd(uP)}${Fx[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).
|
|
103
103
|
|
|
104
104
|
Anywhere the bar shows (?), clicking it reveals these same instructions
|
|
105
|
-
in place. In edit mode: ${
|
|
105
|
+
in place. In edit mode: ${dP.join(`, `)}.
|
|
106
106
|
|
|
107
|
-
Animation lanes (each switched in the settings menu's ${
|
|
108
|
-
${ix.map(e=>` ${rx[e].label}\n${
|
|
107
|
+
Animation lanes (each switched in the settings menu's ${lP}):
|
|
108
|
+
${ix.map(e=>` ${rx[e].label}\n${fP[e].map(e=>` ${e}`).join(`
|
|
109
109
|
`)}`).join(`
|
|
110
110
|
`)}
|
|
111
111
|
|
|
@@ -140,14 +140,14 @@ Subcommands:
|
|
|
140
140
|
${ix.join(`, `)}:
|
|
141
141
|
the experimental lane this stream serves,
|
|
142
142
|
which streams only while its toggle in the settings
|
|
143
|
-
menu's ${
|
|
143
|
+
menu's ${lP} is on.
|
|
144
144
|
bar-pane PANE Draw the bar of the Claude Code session in tmux
|
|
145
145
|
pane PANE (e.g. %3) in this pane, as the daemon
|
|
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
149
|
runs while ${rx.pane.label} is on in the settings
|
|
150
|
-
menu's ${
|
|
150
|
+
menu's ${YM(rx.pane.switch.setting)}.
|
|
151
151
|
|
|
152
152
|
Config tooling:
|
|
153
153
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -173,28 +173,28 @@ Config tooling:
|
|
|
173
173
|
config [--json] The effective merged config. (All three query the
|
|
174
174
|
running daemon; none spawn one.)
|
|
175
175
|
|
|
176
|
-
`,
|
|
177
|
-
`)}function
|
|
178
|
-
`}const Ote=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function HP({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&Ote(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function UP(e){return e.map(e=>e.text).join(``)}const kte={};function WP(e,t){let n=Yl(t.colorSystem),{time:r}=t,i=1/0,a=[...op(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:SP,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:kte}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:Tte(a,n.colorSystem),nextChange:Math.min(G.nextChange(a),i)}}const GP=new Map;function Ate(e){let t=GP.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}=vh.plain,a=new Hm({glyph:n(r.glyph),ascii:r.ascii},i);return GP.set(e,a),a}function KP(e,t){return e===`plain`&&t!==void 0?Ate(t):vh[e]}const qP=new Map;function JP(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=qP.get(t);if(n!==void 0)return n;let r=KP(e.endcaps,e.separator),i=e=>new q(`x`,{end:``,overflow:`ignore`,style:new W({bgcolor:e})}),a=e=>{let{lines:t}=WP(new dm(e,r),{colorSystem:null});return new q(UP(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return qP.set(t,s),s}function YP(e){return JP(e).chrome}function XP(e){return JP(e).seam}const jte=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function ZP(e){return[...new Set(e.match(jte)??[])].join(``)}function Mte(e){let t=KP(e.endcaps,e.separator),n=e=>new q(`x`,{end:``,style:new W({bgcolor:e})}),{lines:r}=WP(new dm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return ZP(UP(r.flat()))}function QP(e){return e.wrap?e.width:1/0}function Nte(e,t){return WP(new q(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(UP)}function $P(e,t,n=wP){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=KP(t.endcaps,t.separator),i=Number.isFinite(QP(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new x_([...e],{joiner:r}):new dm([...e],r),s=n.kind===`still`?WP(o,a):WP(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function Pte(e,t){return BP($P(e,t).lines,t.colorCompatibility)}const Fte=[`moves`,`can-move`,`still`];function eF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const Ite=[`statusline`,`frames`],tF=e=>e?.kind===`frames`?`frames`:`statusline`,Lte=[`carried`,`missing`,`unanswered`];function Rte(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:eF(e)===`no`?`unanswered`:`missing`}function zte(e){return{path:e.transcript_path,answered:eF(e)===`yes`}}const nF=[...Fte,`failed`,`drawing`];var Bte=class{seen=new Map;see(e,t,n,r){let i=tF(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 rF={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`}}},iF=e=>rF[e];function Vte(e){return iF(e).glyphs.kind===`bundled`}function Hte(e){return iF(e).glyphs.kind===`configured`}const aF=e=>iF(e).label,Ute=[{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 Wte(e,t){let n=t.codePointAt(0);return Ute.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&cF(e,t)===!0)}const oF=Object.keys(rF);function sF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function cF(e,t){let n=sF(e),r=sF(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 Gte(e){for(let t of oF){let n=iF(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 lF(e){let t=oF.find(t=>iF(t).term===e);return t===void 0?null:{name:t,version:null}}function Kte(e){let t=Gte(e.termtype)??lF(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 qte(e){let t=e.TERM_PROGRAM,n=oF.find(e=>iF(e).program===t),r=n===void 0?lF(e.TERM):{name:n,version:iF(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 uF(e){switch(e.kind){case`known`:return aF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function dF(e){switch(e.kind){case`known`:return aF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Jte({name:e,version:t}){let n=iF(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=cF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Yte=oF.filter(e=>iF(e).links!==null).map(aF).join(`, `);function fF(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(!us(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||!us(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function pF(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 Xte=[`managed`,`project`],Zte=e=>!Xte.includes(e.scope),Qte={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:ss(t.projectDir)}),user:e=>({scope:`user`,path:e})},mF=[`drawn`,`boxes`],hF=1024*1024,gF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function $te(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 _F(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const vF=Uc.truecolor;function yF(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 ene={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>yF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=pF(t.sources,vF);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:`${vF} 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`,vF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Qte[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 ${vF} to "1" there`}:o(s)})},tne={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>yF(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"})},nne={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:`${gF(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 ${gF(e.value.of)} measured`}},rne={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},ine={argument:`command argument`,environment:`$${_P}`,unknown:`source unknown`};function ane({target:e,layers:t}){return e.source===`search`?t.length===0?xP(t):`${xP(t)} (searched)`:`${e.path} (${ine[e.source]})`}function one(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}" ${rne[e]}`)]}}const sne={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=ane(e),n=_F(one(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},bF="re-run `cc-candybar install`";function cne(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:// — ${bF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${bF}`]}const lne={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 — ${bF}`};case`lost`:return _F([...cne(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 xF({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 SF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${ix.join(`|`)}>\``:e.checkout===null?bF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function une(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 — ${SF(e,`native`)}`];let{bundle:i,source:a}=xF(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} — ${SF(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 — ${SF(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 CF=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)`},dne={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`:`${CF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:_F([...new Set(i.flatMap(e=>une(n,r,e)))])}};function wF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||zr(e.identity,t.value.through)):[]}function TF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const EF={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`?TF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return _F([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=wF(e.value,n),u=_F([...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 ${Ir(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 ${Ir(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Hr(o.charge.bytes,s)?[`the daemon holds ${Kr(o.charge)} of its ${Ir(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}}}},DF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function OF(e,t){let n=uF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Jte(e.terminal):{kind:`unknown`}}function kF({identified:e,tmuxClient:t},n){let r=dF(e),i=OF(e,n),a=uF(e)===null?DF:`${DF}, 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: ${Yte}`];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 AF={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 _F(kF(t,n))}}},jF=e=>e.filter(e=>e.role===`statusline`),MF={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})=>FF(e,NF(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:PF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:CF(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}}},NF=e=>{let t=jF(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, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},PF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function FF(e,t){let n=fF(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 PF(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 Zte(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 IF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function LF(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return dF(e);case`bundling`:case`unread`:case`configured`:return[aF(e.name),e.version].filter(e=>e!==null).join(` `)}}function RF(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return uF(e);case`bundling`:case`unread`:return aF(e.name);case`configured`:{let t=aF(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 zF(e){let t=RF(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${IF(e.glyphs)}`}}const BF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=zF(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=LF(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 ${IF(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=rF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:cF(i.version,e);if(t===!0)return{ok:!0};let n=aF(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 ${IF(n)} — set a Nerd Font as its font`)}}}};function VF(e){return e.join(`, `)}function HF(e){return`or set missingData: "ignore" on ${VF(e)}`}function UF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${VF(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`?[`${VF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${HF(t)}`]:[`${VF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${HF(t)}`]}function WF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${VF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${VF(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`:`${VF(n)}: ${CF(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`)?[`${VF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${VF(n)}`]:[]}const GF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>_F([...UF(e.pullRequests),...WF(e.rateLimits,t)])};function KF({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 ${hF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const qF=[sne,dne,EF,lne,AF,ene,tne,nne,MF,BF,GF,{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`:`${CF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:_F(e.value.flatMap(KF))}],JF=qF.filter(e=>e.takesMark);function YF(e){return qF.map(t=>({check:t,verdict:t.probe(e)}))}function XF(e){return qF.find(t=>t.name===e)}const ZF=`${F}doctor.`;function QF(e){let t=`${ZF}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function $F({target:e}){return`configTarget=${e.source}`}function eI(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?uF(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 tI(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 nI(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}=xF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const rI=e=>`${e>=0?`+`:``}${Ir(e)}`;function iI({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${TF(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`:`${wF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${qr(i.charge)}${i.charge.kind===`stand-in`?`(${rI(-i.charge.gap)})`:``}:${Ir(i.charge.bytes)}`}/${Ir(a)} postMortems=${s}`}function aI(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 oI(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>sI(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=jF(r.flatMap(e=>e.bars));return`frames=${nF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function sI(e){let t=fF(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 cI(e){let t=pF(e,vF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function lI(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 uI(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=zF(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 dI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function fI(e){return e.flatMap(({check:e,verdict:t})=>{let n=QF(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Oy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:dI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Oy:Dy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const pI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function mI(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(pI).map(([t,n])=>[`${e}${t}`,n]))}}const hI=`armed`,gI=`disarmed`,_I=`.armed`,vI=e=>e.endsWith(_I);function yI(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 bI(e,t,n){let r=`${e}${_I}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${hI}")`,s=yI(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:hI},[a]:{set:r,to:gI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:gI}},disarm:a}}const xI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function SI(e){return typeof e==`string`&&xI.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 CI(e){let t=SI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const wI=[`/compact`,`/model`],TI=`/clear`;function EI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=bI(`${e}clear`,{arm:TI,confirm:`${TI} ✓ confirm`},[{action:n,when:`true`}]);return{template:wI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${nx} }}`,actions:{...Object.fromEntries(wI.map(e=>[t(e),{slash:CI(e)}])),...r.actions,[n]:{slash:CI(TI)}},variables:r.variables,disarm:r.disarm}}const DI=Array.from({length:10},(e,t)=>(t+1)*1e5),OI=DI[0],kI=DI[DI.length-1];function AI(e){let t=is(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?I(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=OI&&n<=kI?I(n):R(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${OI}–${kI} tokens)`,`parse`)}function jI(e,t){let n=Math.min(t??kI,kI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:DI.filter(e=>e<r).at(-1)??0,higher:DI.find(e=>e>r&&e<=n)??0}}function MI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${nx} }}{{ 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:CI(`/autocompact auto`)},...Object.fromEntries(DI.map(t=>[`${e}${t}`,{slash:CI(`/autocompact ${t}`)}]))}}}const NI=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 }}`,PI=`${F}edit`,FI=`${F}toolbar`,II=mI(F),LI=`${F}commands`,RI=EI(`${LI}.`),zI=`${F}autocompact`,BI=MI(`${zI}.`,NI),VI=e=>({kind:`segment`,name:e}),HI=`${F}tab`,UI=e=>`${HI}.${e}`,WI=e=>`${UI(e)}.toggle`,GI=e=>({variable:HI,key:HI,member:e}),KI=`${F}save`,qI=`${F}preset.save`,JI=`${F}preset.delete`,YI=e=>`${F}${e}`,XI=e=>`${F}apply.${e}`,ZI=e=>`${F}reset.${e}`,QI=`${F}themeDefault.save`,$I=`${F}themeDefault.differs`,eL=`${F}themeDefault.theme`,tL={when:`{{ .${$I} }}`,template:`{{ action "${QI}" (printf "⤓ default for %s" .${eL}) }} {{ swatch "${XI(`theme`)}" .${eL} }}`},nL=`${F}resetAll`,rL=`${Li}.toggle`,iL=`${F}undo`,aL=`${F}back`,oL=`${aL}.step`,sL=`${F}navigation.back`,cL=aL,lL={template:`{{ if gt .${sL} 0 }}{{ action "${aL}" "◁" }}{{ else }}{{ fg (${pP}) "◁" }}{{ end }}`},uL=`${F}redo`,dL=`${F}doctor`,fL=`${dL}.run`,pL=e=>`${dL}.fix.${e}`,mL=(e,t)=>`${dL}.mark.${e}.${t}`,hL=e=>`${dL}.${e}`,gL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},_L=EM(`${F}pickers`),vL=e=>`${F}${e}`,yL=e=>`${vL(e)}.toggle`,bL=e=>GM(e)?EM(`${F}${e}Pickers`):_L,xL=e=>{let t=bL(WM[HM[e].beside]);return{variable:t,key:t,member:e}},SL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${JI}" (printf "🚮 delete %s" .${Px.preset.effectiveVar}) }}`}},CL=(e,t)=>`${F}list.${e}.${t}`,wL=e=>`${F}resettable.${e}`,TL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${wL(e.name)})`).join(` `)})`,EL=ix.map(e=>[rx[e].switch.setting,e]),DL={variables:{},actions:{},segments:{}},OL=Object.fromEntries(EL.map(([e,t])=>[e,QN(`${F}help.${e}`,dP[t],[],DL)])),kL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],AL=e=>{let t=t=>`.${lx(e,t)}`,n=kL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Px[rx[e].switch.setting].effectiveVar} ${JSON.stringify(rx[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},jL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${Bi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,ML=`${F}fps`,NL=`{{ if eq .${sx(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${sx(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,PL=Object.fromEntries(EL.map(([e,t])=>[e,AL(t)])),FL=e=>UM.filter(t=>HM[t].beside===e),IL=Object.keys(Px).map(e=>{let t=Px[e],n=WM[e];return{...t,name:e,place:n,control:RM({label:t.label,domain:QM(t.configKey)},t.sessionKey,t.effectiveVar,XI(e),bL(n)),beneath:t.previews.map(e=>SL[e]),help:[OL[e]].filter(e=>e!==void 0),submenus:FL(e)}}),LL=e=>IL.filter(t=>t.place===e),RL=e=>IL.filter(t=>KM(t.place,e)),zL=e=>t=>`(print ${Di(t)} (ternary ${Di(` •`)} "" ${TL(RL(e))}))`,BL=e=>LL(e).flatMap(e=>[QL(e),...e.help,...e.submenus.map(e=>Si(vL(e),xL(e),aR(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(IL.flatMap(e=>[e.sessionKey,e.configKey]));const VL=bI(nL,{arm:`⟲`,confirm:`⟲ reset all?`},IL.map(e=>({action:ZI(e.name),when:e.shown}))),HL=[`unsaved`,`history.undo`,`history.redo`],UL=e=>`${F}${e}`,WL=UL(`unsaved`),GL=(e,t)=>({body:t,shown:`(gt .${UL(e)} 0)`}),KL=[GL(`unsaved`,`{{ action "${KI}" (printf "💾 save %d" .${WL}) }}`),GL(`history.undo`,`{{ action "${iL}" "↶" }}`),GL(`history.redo`,`{{ action "${uL}" "↷" }}`),{body:VL.template,shown:`(or ${TL(IL)} ${VL.armed})`}],qL={when:`{{ or ${KL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+KL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},JL=[{step:VL,place:`door`},{step:RI,place:`session`}],YL=e=>e.map(e=>e.step.disarm),XL=YL(JL),ZL=YL(JL.filter(e=>e.place!==`door`));function QL(e){let t=YI(e.name);return e.control.kind===`inline`?VI(t):Si(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>VI(CL(e.name,n)))},`drop`)}function $L(e){return e===Li}function eR(e){let t=VI(Li);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[eR(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 tR(e){return nR(e)>0?e:eR(e)}function nR(e){let t=0;for(let n of zy(e))n.kind===`segment`&&$L(n.name)&&(t+=1);return t}function rR(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&$L(e.name)||e.opens!==void 0&&rR(e.opens.body,!0):e.children.some(e=>rR(e,n))}const iR={door:{direction:`horizontal`,content:[VI(cL)],after:[VI(PI),VI(KI)]},session:{direction:`vertical`,content:[VI(FI),{kind:`container`,direction:`horizontal`,children:[VI(LI),VI(zI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[VI(qI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[VI(dL),...qF.map(e=>VI(hL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[VI(QI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function aR(e){let{direction:t,content:n,after:r}=iR[e];return{kind:`container`,direction:t,children:[...n,...BL(e),...r]}}function oR(e){return e.kind===`segment`?$L(e.name)?{kind:`container`,direction:`horizontal`,children:[Si(e.name,zi,cR,`above`),VI(ML)]}:e:lR(e)}function sR(){return{kind:`container`,direction:`vertical`,children:[aR(`door`),{kind:`container`,direction:`horizontal`,children:BM.map(({member:e})=>Si(UI(e),GI(e),aR(e),`drop`))}]}}const cR=sR();function lR(e){return{...e,children:e.children.map(e=>oR(e))}}function uR(e){let t={variables:{[Li]:Oi(Li,P),[Bi]:{kind:`state`,key:Bi,default:`0`}},actions:{[rL]:ki(Li,Ri),[Bi]:{set:Bi,int:!0},[Li]:{do:[rL,...XL]},[fL]:{doctor:`run`},...II.actions,...RI.actions,...BI.actions,[KI]:{save:!0},[iL]:{undo:!0},[oL]:{back:!0},[aL]:{do:[oL,...XL]},[uL]:{redo:!0},[qI]:{preset:`save`},[QI]:{themeDefault:`save`},[JI]:{preset:`delete`,name:`{{ .${Px.preset.effectiveVar} }}`}},segments:{[Li]:{template:`{{ $door := ${Ei(Li,Di(e),Di(`✖`))} }}{{ if ${wi(zi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+jL},[ML]:{template:NL},[FI]:{template:II.template},[LI]:{template:RI.template,when:RI.when},[zI]:{template:BI.template,bg:BI.bg,when:BI.when},[cL]:lL,[KI]:qL,[QI]:tL,[qI]:{template:`{{ action "${qI}" "+ preset" }}`},[dL]:{template:`{{ action "${fL}" "🩺 doctor" }}`},[PI]:{template:`{{ action "${HN}" "✎ arrange" "✎ done" }}`}}};t.variables[$I]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[eL]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[sL]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of HL)t.variables[UL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[HI]=Oi(HI,P);for(let{member:e,label:n}of BM){t.actions[WI(e)]=ki(HI,e),t.actions[UI(e)]={do:[WI(e),...ZL]};let r=zL(e);t.segments[UI(e)]={template:`{{ ${Ei(UI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,RI.variables,VL.variables),fR(t),dR(t),t}function dR(e){for(let t of qF){let n=QF(t.name),r=pL(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?mF:[];for(let n of i)e.actions[mL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${mL(t.name,e)}" "${gL[e]}" }}`).join(``);e.segments[hL(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} "${Dy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function fR(e){for(let t of IL){Object.assign(e.actions,t.control.actions);let n=ZI(t.name);e.actions[n]={reset:t.configKey},e.variables[wL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${wL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[YI(t.name)]={template:`${t.control.template}${PL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[CL(t.name,r)]=n})}Object.assign(e.actions,VL.actions),Object.assign(e.variables,DL.variables),Object.assign(e.actions,DL.actions),Object.assign(e.segments,DL.segments);for(let t of UM){let n=xL(t);e.actions[yL(t)]=ki(n.key,n.member),e.segments[vL(t)]={template:`{{ action "${yL(t)}" ${zL(t)(HM[t].trigger)} }}`}}}function pR(e){let{variables:t,actions:n}=ZN();Object.assign(e.variables,t),Object.assign(e.actions,n)}function mR(e){let t=uR(e.globals.menuGlyph??`🍫`);pR(t);let n={...e.presets},r=[];for(let t of fS(e.presets)){let{node:i}=hS(e,t),a=oR(tR(i));r.push(a),n[t]={...mS(e.presets,t),root:a}}let i=SM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const hR=`${Pi}live`,gR=[`☐ live`,`☑ live`],_R=`${Pi}done`,vR=`${Pi}cancel`,yR=`${Pi}rewind`,bR=`${Pi}changes`,xR=`(gt .${bR} 0)`,SR=`(or ${xR} (gt .${WL} 0))`,CR={variable:hR,key:hR,member:_i};function wR(e){return`${Pi}configuring.p${e}`}function TR(e){return`and ${wi(KN)} (not ${wi(CR)}) (ne .${wR(e)} "true")`}function ER(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${VN} "${xi(e)}")`).join(` `)} false }}`}}function DR(e,t,n){return`{{ if ${TR(e)} }}${t}{{ else }}${n}{{ end }}`}const OR=`{{ and ${wi(KN)} .preset.customized }}`,kR=Ii;function AR(e){return new Map([...SS(e),...MR(e)])}const jR=`${Pi}addable`;function MR(e){return new Map([[jR,{members:Object.keys(e.segments).filter(e=>!kR(e)),library:{groups:PN.map(e=>({id:e,label:FN[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function NR(e,t,n){return n.segments[e]={template:t,when:qN,bg:eP},{kind:`segment`,name:e}}function PR(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) ${Cv}`}) (action "${r}" "✖") }}`}function FR(e){return`{{ if ${wi(KN)} }}${e}{{ end }}`}function IR(e,t){return e.reduce((e,t)=>`{{ if and ${wi(KN)} ${wi(t)} }}true{{ else }}${e}{{ end }}`,t)}function LR(e){return e.flatMap(e=>[...zy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function RR(e,t,n){return`${WN}${e}.${t}.${n}`}function zR(e,t,n,r){let i=Fy(n),a=`${Pi}${e.presetIdent}`,o=GN(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=EM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:VN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=RR(e.presetIdent,i,r),l=`${WN}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:ab(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=RM(IM(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}" "${oP}" }}`,ref:{variable:VN,key:VN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const BR=`${Pi}label:`;function VR(e){if(e.startsWith(BR)){let t=e.slice(BR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function HR(e,t,n,r){let i=Fy(e),a=UR(n,i,e,t,i),o=Object.fromEntries(eb.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Si(a,r.ref,r.body,`drop`,IR([r.ref],`{{ ${TR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(eb.map(e=>[e,r.drafts[e]]))}}function UR(e,t,n,r,i){let a=`${BR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${xi(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function WR(e,t,n,r){let i=Fy(e),a=n?[qR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=qR(r,o,i,`after`),c=PR(r,o,i),l=r.segments[e.name],u=zR(r,o,e,tb(l)),d=FR(c),f=FR(u.term);return[...a.map(e=>NR(e.host,e.template,r.artifacts)),{...HR(e,l,r,u),lead:d,trail:f},{...t,when:DR(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},NR(s.host,s.template,r.artifacts)]}function GR(e){return T.join(T.basename(T.dirname(e)),T.basename(e))}function KR(e,t,n,r){let i=r.segments[e.name],a=Fy(e);return[{kind:`segment`,name:UR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${GR(t.file)} ${t.entry}`),when:`{{ ${TR(r.presetIdent)} }}`},{...n,when:DR(r.presetIdent,`false`,e.when??`true`)}]}function qR(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:jR,anchor:n,relation:r};let c=wM(o),l=TM(s,o,void 0),u=OM(l),d=DM(l,c);return a.variables[l]={...Oi(l,P),within:[KN]},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) ${Cv}`}) $m }}{{ end }}`}}function JR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!kR(e.name)&&e.insertedBy===void 0),i=e=>JR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Ry(o,i);if(kR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?WR(o,s,a===r,t):KR(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:IR(LR(n),DR(t.presetIdent,`true`,e.when))}}}function YR(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:OR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},XR(e,o)]}}function XR(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),XR(n,t)]}:{...e,children:[...e.children,t]}}function ZR(e,t,n,r,i,a){let{node:o}=hS(e,t),s={presetIdent:CM(t),rootKey:DN(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=JR(o,s);return n.variables[wR(s.presetIdent)]=ER(s.configured),YR(c,s.presetIdent,s.rootKey,n,r,i,a)}function QR(e){let t={variables:{},actions:{},segments:{}},n=QN(`${Pi}help`,uP,[KN],t);t.variables[hR]=Oi(hR,P),t.actions[hR]=ki(hR,CR.member),t.segments[hR]={template:Ti(hR,...gR),when:qN};let r={kind:`segment`,name:hR},i=n;t.variables[bR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[_R]={do:[KI,HN]},t.segments[_R]={template:`{{ if ${SR} }}{{ action "${_R}" "✓ save" }}{{ else }}{{ action "${_R}" "✓ done" }}{{ end }}`,when:qN},t.actions[yR]={rewind:!0},t.actions[vR]={do:[yR,HN]},t.segments[vR]={template:`{{ action "${vR}" "↩ cancel" }}`,when:`{{ and ${wi(KN)} ${xR} }}`};let a=[{kind:`segment`,name:_R},{kind:`segment`,name:vR}],o={...e.presets},s=[];for(let n of fS(e.presets)){let c=ZR(e,n,t,a,r,i);s.push(c),o[n]={...mS(e.presets,n),root:c}}let c=SM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function $R(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function ez(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 tz(e,t,n){let r=Ly(e,new Set(n.map(Iy).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const nz=/^-?\d+$/;function rz(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 iz(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!nz.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 az(e,t,n){return r=>r?nz.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 oz(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=>!nz.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 sz(e){return e===`config`?`set-config`:`set-state`}function cz(e,t,n){return t.kind===`int`?iz(`menu page "${e}"`):t.kind===`range`?az(t.min,t.max,`${n} stepper "${e}"`):rz(t.allowed,`${n} "${e}"`,sz(n))}function lz(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:oz(e,n,t)}))}function uz(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 lz(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,cz(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 dz(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};uz(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=uz(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function fz(){return dz({},`config`,gz)}function pz(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:wS(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:[$R({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[$R({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:wS(e.insertSegmentFrom,t).members.map(t=>$R({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function mz(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?jN(n.persist):null;e?.scope===`preset-root`&&t.add(DN(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function hz(e){let t=AR(e);return[...mz(e),...Object.values(e.actions).flatMap(e=>pz(e,t))]}function gz(e){return lz(hz(e),`config`)}const _z=Zv(),vz=new Set(_z),yz=new Set(yy),bz=e=>e?vz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${_z.join(`, `)})`}:{ok:!1,reason:`theme name is required`},xz=e=>e?yz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${yy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},Sz=new Set([`1`,`true`]),Cz=new Set([`0`,`false`]),wz={endcaps:xz,theme:bz,"toolbar-expanded":e=>Sz.has(e)?{ok:!0,value:`1`}:Cz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function Tz(){return dz(wz,`state`,kz)}function Ez(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:wS(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 Dz(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(wz,e.key))}function Oz(e){let t=AR(e);return Dz(Object.values(e.actions).flatMap(e=>Ez(e,t)))}function kz(e){return lz(Oz(e))}function Az(e){let t=Tz(),n=fz();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 jz=`update.dismissed`,Mz=`updateNotice`,Nz=Px.updateNotice.sessionKey;function Pz(){return Az({config:[{key:Mz,allowed:[`false`]}],state:[{key:Nz,allowed:[`false`]},{key:jz,allowed:[]}]})}function Fz(e){try{return s.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Iz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:zz(t.segments,Lz(t.segments,e.segments??{})),root:rS(e.root??Zx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:zz(t.presets,Rz(t.presets,e.presets??{})),themeDefaults:zz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Lz(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 Rz(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 zz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Bz=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 Vz(e){let t=Bz.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 Hz(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: ${Gy.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Gz(e,`${t}.cache`,n.cache)}function Uz(e){return{required:!0,json:Kz(),parse:(t,n,r,i)=>Hz(t,n,i,e)??void 0}}const Wz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Jz(n)?{ttl:n}:Fb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${kb(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Fb(e,t,`cache.watch_file must be a path string, got ${kb(n)}`);let r=qb(`cache.watch_file`,n);return r===null?{watch_file:n}:Fb(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}:Fb(e,t,`cache.depends_on must be an array of variable-name strings, got ${kb(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Fb(e,t,`cache.key must be a non-empty template string, got ${kb(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Fb(e,t,`cache.never must be the literal boolean true, got ${kb(n)}`)}}};function Gz(e,t,n){return Ib(e,Wz,t,n)}function Kz(){return ex(Wz)}const qz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Jz(e){return qz.test(e)}const Yz=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 Xz(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 Zz(e){let t=Yz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Xz(t)}`}function Qz(e){let t=Yz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Xz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const $z=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`]]),eB=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 tB(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 nB(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`?eB.get(e.field):void 0;if(n===void 0){let e=[...eB.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 ${tB(n.declare)} under a name of your own`}const rB=new Map([[`load-config`,`the load-config verb is removed — a session's config is the file its statusline command names with --config, else the file its shell names in $${_P}; point the session there instead of linking to a path`]]);function iB(e){let t=rB.get(e);return t===void 0?void 0:`Template spells "${Vi}://${e}/…", a URL no click runs: ${t}`}function aB(e,t,n){if(n===void 0)return{};if(!Db(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Ob(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Lb(e,OB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function oB(){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 ${Ob(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function sB(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Cb(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const cB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Fb(e,t,`parse.text must be the literal boolean true, got ${kb(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?lB(e,t,n):Fb(e,t,`parse.regex must be a pattern string, got ${kb(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Fb(e,t,`parse.json must be the literal boolean true, got ${kb(n)}`)}}};function lB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Fb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Fb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function uB(){return{required:!1,json:ex(cB),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:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ib(e,cB,`${t}.parse`,r.parse)??void 0)}}function dB(){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)=>Db(r.parse)&&`json`in r.parse?fB(e,t,r.default):wb(e,t,r,`default`)}}function fB(e,t,n){if(n!==void 0)return pB(n)?n:Fb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${kb(n)}`)??void 0}function pB(e){return e!==null&&CC(e)}const mB={value:oB(),default:Vb()};function hB(){let e=Kb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:$z.get(a);return o===void 0?a:Fb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const gB={path:hB(),type:Yb([`string`,`number`,`boolean`]),default:sB()},_B={name:Kb(),default:Vb()},vB={path:Jb(),readMode:Yb([`whole`,`first-line`]),parse:uB(),cache:Uz(`file`),default:dB()},yB={command:Kb(),parse:uB(),cache:Uz(`shell`),default:dB()};function bB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const xB={template:Kb(),type:Yb([`string`,`number`,`boolean`]),default:sB()},SB=bB(`a template variable recomputes whenever a variable it reads changes`),CB={layout:Kb(),default:Vb()},wB=bB(`a time variable reads the instant its render is drawn at`),TB={key:Kb(),default:Vb()},EB=`kind`;function DB(e,t,n={}){return{...Rb(EB,e,t),parse:(r,i,a)=>{jb(r,n,i,a);let o=Mb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const OB={tag:EB,noun:`source kind`,memberNoun:`variable`,arms:{literal:DB(`literal`,mB),input:DB(`input`,gB),env:DB(`env`,_B),file:DB(`file`,vB),shell:DB(`shell`,yB),template:DB(`template`,xB,SB),time:DB(`time`,CB,wB),state:DB(`state`,TB)},retired:{git:nB}};function kB(){return $b(OB)}function AB(){return{type:`object`,additionalProperties:kB()}}const jB=/^[A-Za-z_][A-Za-z0-9_]*$/,MB={pattern:jB.source},NB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},PB={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`,...MB}}}]},default:NB}},FB=[`label`,`domain`,`default`],IB=[`min`,`max`,`step`,`atLeast`];function LB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function RB(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 LB(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 LB(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?LB(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(Db(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!IB.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}}:LB(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 LB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${kb(n)}`)}function zB(e,t,n){if(!Db(n))return LB(e,t,`${t} must be { label, domain, default }, got ${Ob(n)}`);for(let r of Object.keys(n))FB.includes(r)||LB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${FB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||LB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${kb(r)}`);let a=RB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!BB(n.default)||!ib(o,n.default)?LB(e,`${t}.default`,`default must be ${cb(o)}, got ${kb(n.default)}`):o}function BB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const VB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Qy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function HB(e){return eb.includes(e)}function UB(){return{required:!1,json:{type:`object`,propertyNames:{...MB,not:{enum:[...eb]}},additionalProperties:PB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Db(i))return LB(e,a,`${a} must be an object of name → { label, domain, default }, got ${Ob(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!jB.test(t)){LB(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(HB(t)){LB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${VB[t]}`);continue}let r=zB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const WB=Fi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function GB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${WB})[^:/]+$`},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:LB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Fi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${kb(i)}`)}}}function KB(){return{required:!1,json:{type:`object`,propertyNames:MB,additionalProperties:NB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Db(i))return LB(e,a,`a placement's "settings" must be an object of setting name → value, got ${Ob(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))BB(n)?o[t]=n:LB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Ob(n)}`);return o}}}function qB(e){return new Set(Object.keys(e.segments).filter(e=>!Ii(e)))}function JB(e,t,n){if(t===void 0)return{};if(!Db(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Ob(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Ab(e,n.has(i)?iV:rV,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function YB(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 ${Ob(s)}`,line:J(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),n])})}const XB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function ZB(){return{required:!0,json:XB,parse:(e,t,n,r)=>r[n]===void 0?Fb(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${Vz(t.slice(9))}`)??void 0:YB(e,t,n,r)}}function QB(){return{required:!1,json:XB,parse:(e,t,n,r)=>r[n]===void 0?void 0:YB(e,t,n,r)}}function $B(){return{required:!1,json:{type:`object`,additionalProperties:XB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Db(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${Ob(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=YB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function eV(){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 ${kb(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function tV(){return{required:!1,json:AB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return aB(e,`${t}.${n}`,i)}}}const nV={template:ZB(),description:Vb(),group:Yb(NN),width:eV(),justify:Yb(lb),truncate:Yb(ub),bg:Vb(),fg:Vb(),when:Vb(),palette:Gb(),vars:tV(),settings:UB(),missingData:Yb(Yy),partials:$B()},rV={noun:`segment key`,fields:nV},iV={noun:`segment key`,fields:{...nV,template:QB()}};function aV(e,t){if(t===void 0)return{};if(!Db(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Ob(t)}`,line:J(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 ${kb(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function oV(e,t,n){if(t===void 0)return{};if(!Db(t))return X(e,`actions`,`actions must be an object, got ${Ob(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=sV(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function X(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function sV(e,t,n,r){if(!Db(n))return X(e,t,`${t} must be an action object, got ${Ob(n)}`),null;if(`persistWhen`in n)return X(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=DS.filter(e=>e in n);return i.length===1?lV(r)[i[0]](e,t,n):(X(e,t,`action must declare exactly one of: ${DS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function cV(e){return e===`<default>`?{dir:null}:T.isAbsolute(e)?{dir:T.dirname(e)}:{text:e}}const lV=e=>({set:(e,t,n)=>GV(e,t,n,`set`,VV),persist:(e,t,n)=>GV(e,t,n,`persist`,HV),copy:uV(`copy`),open:uV(`open`),reset:dV,undo:pV(`undo`),redo:pV(`redo`),back:pV(`back`),rewind:pV(`rewind`),save:pV(`save`),preset:mV,themeDefault:hV,doctor:_V,slash:vV,run:xV(e),do:SV});function uV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Sb(t,n,r,e);return i===null?null:{[e]:i}}}function dV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=CV(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 fV={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 pV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(X(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${fV[e]}), got ${kb(r[e])}`),null)}}function mV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return X(e,`${t}.preset`,`preset must be "save" or "delete", got ${kb(r)}`),null;if(r===`save`)return{preset:`save`};let a=Sb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function hV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(X(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${kb(n.themeDefault)}`),null)}const gV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function _V(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(gV,r),a=i?gV[r]:[...new Set(Object.values(gV).flat())];for(let r of Object.keys(n))a.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return X(e,`${t}.doctor`,`doctor must be ${Object.keys(gV).map(e=>`"${e}"`).join(`, `)}, got ${kb(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?JF:qF;if(typeof o!=`string`||!s.some(e=>e.name===o))return X(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${kb(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return mF.includes(c)?{doctor:`mark`,check:o,mark:c}:(X(e,`${t}.mark`,`doctor mark must be ${mF.map(e=>`"${e}"`).join(` or `)}, got ${kb(c)}`),null)}function vV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=SI(n.slash);return r.kind===`refused`?(X(e,`${t}.slash`,r.reason),null):{slash:r.line}}const yV=[`run`,`env`,`refreshes`],bV=/^[A-Za-z_][A-Za-z0-9_]*$/;function xV(e){return(t,n,r)=>{for(let e of Object.keys(r))yV.includes(e)||X(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${yV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&X(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${kb(a)}`);let o=r.env??{};(!Db(o)||Object.entries(o).some(([e,t])=>!bV.test(e)||typeof t!=`string`))&&X(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${kb(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&X(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${kb(s)}`),`dir`in e||X(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}}}bV.source;function SV(e,t,n){for(let r of Object.keys(n))r!==`do`&&X(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===``)?(X(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 ${kb(r)}`),null):{do:r}}function CV(e,t,n,r,i,a){let o=Sb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(X(e,s,i),null):o.includes(`/`)?(X(e,s,a(o)),null):o}const wV={set:`the SessionState key to write`,persist:`the config globals field to write`};function TV(e,t,n,r){let i=wV[r],a=CV(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 EV(e){return e===`set`?`set-state`:`set-config`}const DV={to:KV(`set`)},OV={to:KV(`persist`)},kV={from:qV(`set`)},AV={from:qV(`persist`)},jV={min:QV(),max:QV(),by:QV()},MV={int:YV()},NV={cycle:JV(`set`)},PV={cycle:JV(`persist`)},FV={removeSegment:XV(`removeSegment`)},IV={insertSegment:XV(`insertSegment`),anchor:XV(`anchor`),relation:ZV()},LV={insertSegmentFrom:qV(`persist`),anchor:XV(`anchor`),relation:ZV()},RV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},zV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function BV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Mb(e,t,n,r),c=Xb(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?Bb(s,...n):s}}const VV=[BV(`set`,DV),BV(`set`,kV),BV(`set`,jV,[RV,zV]),BV(`set`,MV),BV(`set`,NV)],HV=[BV(`persist`,OV),BV(`persist`,AV),BV(`persist`,jV,[RV,zV]),BV(`persist`,PV),BV(`persist`,FV),BV(`persist`,IV,[],[`insertSegment`]),BV(`persist`,LV,[],[`insertSegmentFrom`])];function UV(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 WV(e){let t=UV(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 GV(e,t,n,r,i){let a=TV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return X(e,t,`${WV(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)||X(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 KV(e){let t=EV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>CV(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 qV(e){let t=EV(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===``){X(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){X(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===``)){X(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){X(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){X(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}X(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${kb(o)}`)}}}function JV(e){let t=EV(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`)){X(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Ob(o)}`);return}let c=o;if(c.length<2){X(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){X(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){X(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){X(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function YV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){X(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${kb(r[n])}`);return}return!0}}}function XV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Sb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){X(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){X(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 ZV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){X(e,`${t}.${n}`,`relation must be "before" or "after", got ${kb(i)}`);return}return i}}}function QV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){X(e,`${t}.${n}`,`${n} must be an integer, got ${kb(i)}`);return}return i}}}function $V(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const eH=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),tH=`plugin.json5`,nH=/^[a-z][a-z0-9_]*$/;function rH(e,t){let n=T.basename(T.dirname(e));return nH.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function iH(e){return`${e}.data`}function aH(e){return`${e}.json`}function oH(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:sH(e)}}}function sH(e){return e instanceof db?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 cH(e,t,n,r){return e.map(e=>rH(hP(T.dirname(t),e,r),n))}function lH(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:NS(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(T.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${tH}, and the folder's name is the plugin's: move this file to <dir>/<name>/${tH} and list that`;return c(t,o===void 0?e.config:dH(uH(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${T.basename(T.dirname(a))}" is not a plugin name (one matching ${nH}: 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=uH(e.config,o),d=oH(()=>{let i=s.readFileSync(a,`utf-8`),c=Iz(_H(a,n,{source:i,json:Ia.default.parse(i)},t),u);return MH(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,dH(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function uH(e,t){let n=PS(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 dH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:$V(n),definition:n.path}}}}function fH(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})=>PS(t)(e))}function pH(e,t){let n=fH(e.config),r=[...e.rendering.keys()].map(PS),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=IS(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:$V(e)})):[{definition:a.definition,notice:a.notice}]}}function mH(e,t,n){let r=fS(e.presets).flatMap(t=>[...zy(hS(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,hH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=fH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...xH.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=>rC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...fC(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 hH(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,gH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function gH(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 _H(e,t,{source:n,json:r},{checkout:i,home:a}){let o=NS(t),c=[],l=()=>{throw new db(e,c)};if(!Db(r))return c.push({path:``,message:`a plugin definition must be an object, got ${Ob(r)}`}),l();for(let t of Object.keys(r))eH.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${T.basename(T.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...eH].join(`, `)}`});let u=r.data===void 0?void 0:FH(r.data,e,i,a,c),d=r.sources===void 0?{}:jH(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(Zv()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:aB(f,`data`,{[iH(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=aB(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 (.${iH(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,...wH(o,d),...wH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,EH(o,t)])))},segments:wH(o,DH(o,JB(f,r.segments,new Set))),helpers:wH(o,aV(f,r.helpers)),actions:wH(o,OH(o,oV(f,r.actions,{dir:s.realpathSync(T.dirname(e))})))};c.push(...SH(h,t));let g=vH(o,h);for(let[e,t]of CH(g))try{IN.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),g}function vH(e,t){let n=t=>mC(t,FS,e),r=t=>PS(`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=>yH(qy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(xH.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=>yH(qy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>bH(AS(e,n),r))}}function yH(e,t){return Ky(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function bH(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 xH=[`template`,`bg`,`fg`,`when`];function SH(e,t){let n=e.helpers??{},r=MS.filter(e=>e!==t.scope).map(e=>({scope:e,ns:NS({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>PS(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 ${NS(t)}: a plugin names itself without its scope — write ${s}${FS}${n.slice(o.ns.length)}`})},o=[...[...CH(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 $S(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of rC(t,n))i===null&&a(e,r,!1);for(let n of fC(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))bH(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(Ky(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*CH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of Jy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of xH){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 Jy(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 kS(n))yield[`actions.${t}.${e}`,r]}function wH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function TH(e,t){return`${e}.${t}`}function EH(e,t){return t.kind===`state`?{...t,key:TH(e,t.key)}:t}function DH(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,EH(e,n)]))}]))}function OH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:TH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>TH(e,t))}:n]))}const kH=nH,AH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function jH(e,t,n){if(!Db(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${Ob(e)}`}),{};let r=T.join(s.realpathSync(T.dirname(t)),`session`),i=JSON.stringify(AH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!kH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${kH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=PH(o,AH,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 MH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=NH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=PS(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 db(e,a)}function NH(e){return T.join(e.storage,aH(`<session id>`))}function PH(e,t,n){return!Db(t)||!Db(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)?PH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function FH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return hP(T.dirname(t),e,r);if(Db(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(T.isAbsolute(t)||t.startsWith(`~`)||T.normalize(t).split(T.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 T.resolve(n.root,t)}if(Db(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 IH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>T.join(e,`cc-candybar`,`plugins`)),LH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:T.join(t,RH),scope:`repo`}]]}function LH(e){return T.join(e.dataHome,`cc-candybar`,`plugins`)}const RH=T.join(`.cc-candybar`,`plugins`);function zH(e,t){let n=IH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=BH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=rH(T.join(e,i,tH),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:T.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${tH}: move this file to ${T.join(e,`<name>`,tH)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function BH(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()||VH(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 VH(e,t){if(!t.isSymbolicLink())return!1;try{return s.statSync(T.join(e,t.name)).isDirectory()}catch{return!0}}const HH=[`approved`,`declined`];function UH(e){return e.link.kind===`linked`?e.link.main:e.dir}const WH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function GH(e,t){let n=UH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=WH(e.value,n),i=WH(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 KH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...GH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&GH(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 qH(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 JH(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(!HH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${HH.join(` or `)}`};return{kind:`ok`,value:e}}function YH(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 XH(e){let t=YH(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 ZH=[`json5`,`json`];function QH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?ZH.map(e=>T.join(t,`${$H}.${e}`)):[],...ZH.map(e=>T.join(i,`${$H}.${e}`)),...ZH.map(t=>`${eU(e)}.${t}`)])]}const $H=`.cc-candybar`;function eU(e){return T.join(e.configHome,`cc-candybar`,`config`)}function tU(e){return{path:e,scope:`plugins`}}function nU(e,t,n,r,i){let a=[],o=new Map;for(let t of QH(e,n,r,i)){let n=Fz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=s.realpathSync.native(T.dirname(t)),c=T.join(r,T.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||rU(e,t)?null:{dir:r,link:Vc(r)}})}let c=[...o.values()],l=KH(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),iU(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:aU(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 rU(e,t){return ZH.some(n=>t===`${eU(e)}.${n}`)}function iU(e){if(e===void 0||Fz(e)!==`present`)return null;let t=BH(T.join(e,RH)),n=s.realpathSync.native(e);return{dir:n,link:Vc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function aU(e,t){return t.find(t=>rU(e,t.path))?.path??`${eU(e)}.${ZH[0]}`}function oU(e,t,n,r,i){let a=nU(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 sU(e){return cU(e).join(`
|
|
180
|
-
`)||null}function cU(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 lU(e,t,n){let r=QH(e,t,n).filter(e=>Fz(e)===`present`),i=new Map;for(let e of r){let t=T.dirname(e),n=T.basename(e).replace(/\.(json5|json)$/,``),r=T.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 uU(e,t,n,r){let i=T.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&&On(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const dU={level:`error`,glyph:`⚠`,colors:AP},fU={level:`warning`,glyph:`⚠`,colors:jP},pU={level:`warning`,glyph:`⬆`,colors:jP},mU={level:`warning`,glyph:`🔒`,colors:jP},hU={level:`warning`,glyph:`🧪`,colors:jP};function gU(e,t){return{text:NP(e),link:t}}function _U(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=vU(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,dU)),...r,...i.flatMap(e=>o(e,fU))],c=yU(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[gU(n.lines[0][0].text,bU(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function vU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>gU(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 yU(e){return wU(e).map(e=>String(e*SU+1))}function bU(e,t,n,r){return Ta([{verb:ma,args:[e,t,n]}],`copy diagnostic ${r}`)}function xU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const SU=4096;function CU(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 wU(e){let t=new Map;return e.map(e=>{let n=CU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function TU(e,t,n){return String(wU(e)[t]*SU+n+1)}const EU={error:AP,warning:jP};function DU(e){let t=xU(e),n=e.length,r=EU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:TU(e,0,0)}}function OU(e,t){let n=Number(e)-1,r=wU(t).indexOf(Math.floor(n/SU));return e===null||r===-1?null:{index:r+1,page:n%SU}}function kU(e,t){return Math.min(20,e??20,...t)}function AU(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=NU(i),c=IU(o,s,[]),l=new W({bgcolor:o.severity.colors.bg,color:o.severity.colors.fg}),u=(e,t)=>PU(e,t===null?l:l.withLink(t)),d=(t,r)=>r===null?u(` `,null):u(t,MU(n,TU(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),f=(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,f=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return FU([u(`✕`,MU(n,`0`)),...l?[d(`‹`,o)]:[],u(f,null),...l?[d(`›`,c)]:[],u(`⧉ copy`,bU(n,r,TU(e,a-1,0),a))],s)},p=1;for(;;){let e=Math.max(1,i.rows-p),n=Math.min(SU,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=f(n,r);if(a.length>p){p=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,d=r===n-1&&l>0?[...o.slice(0,-1),...FU([u(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...d]}}function jU(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=DU(t),c=i===``?[]:[PU(i,new W({bgcolor:o,color:a}).withLink(MU(n,s)))];return IU(e,NU(r),c)}function MU(e,t,n){return Ta([{verb:Wi,args:[e,Bi,t]}],n)}function NU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const PU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),FU=(e,t)=>$P(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function IU(e,t,n){let r=new W({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=bl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=PU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Cl(e,a)).map(t=>PU(t,i(e.link)))),u=s===0?n:[];return FU([c,...l,...u],t)})}const LU=`repo-configs.json`;function RU(e){return T.join(e,`repo-configs`)}function zU(e){return T.join(RU(e),LU)}const BU=e=>{let t=uU(RU(e),LU,{},JH),n=uU(e,LU,{},JH),r=()=>s.existsSync(zU(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 VU(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:Fz(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&UH({dir:e,link:Vc(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]:[])},qH(e,t,n,r.superseded)});return i.kind===`failed`?i:I(r)}function HU(e,t,n){return{sessionId:e,action:pa,declaration:t,evaluated:n}}function UU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=HH.map(r=>gU(`[${r===`approved`?`approve`:`decline`}]`,Ta([{verb:pa,args:[t,e,r,n.sign(HU(t,e,r))]}]))),a=[gU(r,null),...i];return{severity:mU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function WU({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const GU=`render-origin`,KU=`client-hints`;function qU(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const JU={kind:`hidden`},YU={kind:`shown`};function XU(e,t){try{return qU(e,t)?YU:JU}catch(e){let t=AC(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function ZU(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function QU(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function $U({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function eW({text:e,placement:t,lead:n,trail:r}){return{text:tW(e),placement:t,...n!==void 0&&{lead:tW(n)},...r!==void 0&&{trail:tW(r)}}}function tW(e){let t=e.blankCopy(e.plain);t.style=CP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(CP(i).clearMetaAndLinks(),n,r);return t}function nW(e){let t=$U(e);if(t.length===1)return e.text;let n=ZU(t);return n.style=e.text.style,n}function rW(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=ZU(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:ZU([d,...c],a)},...l.length>0&&{trail:ZU([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(QU(u,n,p),[{text:u,...f}])}function iW(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return Nte(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 aW(e,t){if(e.length===0)return 0;let{lines:n}=$P(e.map(({owner:e})=>e),t),r=B(UP(n[n.length-1]));return Math.max(0,r-YP(t)+XP(t))}function oW(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=$P([e],{...n,width:1/0});return B(UP(r.flat()))<=n.width}function sW(e,t,n,r){if(oW(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=aW(n,r);return i.divide(iW(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 cW(e,t){let n=Math.max(2,QP(t)-YP(t)-t.padding);return lW(e,t).reduce((e,r)=>[...e,...sW(r,n,e,t)],[])}function lW(e,t){let n=()=>e.map(e=>({owner:nW(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=$P(e.map(nW),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(UP(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];QU(c,c.cellLength+a,n)}),n()}function uW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=dW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:CP(a.style)};if(e.style.link){i();let r=dW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function dW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>fW(e.frag,n?n.add(e.style):e.style)),i=q.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function fW(e,t){let n=e.copy();return n.style=t,n}function pW(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 mW(e,t){let{look:n}=pW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function hW(e,t){let{layout:n}=pW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function gW(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 _W(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,vW(e,t,o,n,r,i));return i}function vW(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=wS(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=Rx.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=wS(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=wS(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:xW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:xW(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:OS(n),argv:n.run.map(n=>xW(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,xW(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:xW(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 yW(e){return e.kind===`do`?yW(e.head):e}function bW(e){switch(yW(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 xW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function SW(e,t){return e.has(t)?EC(e.read(t)):``}function CW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function wW(e,t,n,r){let i=new q(e,{style:W.combine([r,new W({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function TW(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([CP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([CP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function EW(e,t){return Math.max(e.members.indexOf(SW(t,e.stateVar)),0)}function DW(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=SW(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=SW(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=SW(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(EW(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:[CW(e.text,$A(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[CW(e.target,$A(r))]}],active:!1};case`persist-literal`:{let t=SW(r,e.stateVar);return{effects:[{verb:Yi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=SW(r,e.stateVar);return{effects:[{verb:Yi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(EW(e,r)+1)%e.members.length];return{effects:[{verb:Yi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Xi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ta,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ra,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`back`:return{effects:[{verb:aa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:oa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Zi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ea,args:[i,CW(e.name,$A(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ca,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:la,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:ua,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:fa,args:[i,e.line]}],active:!1};case`run`:{let t=$A(r),n=JSON.stringify({run:e.argv.map(e=>CW(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,CW(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:na,args:[i,e.key,$R(e.op)]}],active:!1};case`do`:{let o=DW(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>DW(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:na,args:[i,e.key,$R(r)]}],active:!1}}}}function OW(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,EW(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 kW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=pW(n,`action "${e}"`).store,{display:a,boundValue:o}=OW(e,yW(r),t,i),s=SW(i,`session.id`),{effects:c,active:l}=DW(r,a.plain,o,i,s,n.signer);return TW(a,Ta(c),l)}function AW(e){return{action:{fn:(t,...n)=>kW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function jW(e,t){return wW(`✕`,Ta([{verb:Wi,args:[SW(e,`session.id`),t,P]}]),!1)}function MW(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(wv(e,t,n))})}function NW({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function PW(e,t,n){return new W({color:U.fromRgba(ld(e.get(`warning`),t,Cv,n))})}function FW(e,t,n){return W.combine([MW(e,t,n),PW(e,t,n)])}function IW(e,t,n){return NW(Iv(e.palette,e.disclosure,t,n))}function LW(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(E_.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const RW=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},zW=e=>new W({bold:e});function BW(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>RW(a,W.combine([IW(e,{...n,distribution:t},i),zW(o)]));let o=MW(e.palette,a,i);return(e,t,i,a)=>VW(i,W.combine([o,zW(a)]),r(t,n))}const VW=(e,t,n)=>RW(q.fromFragments([RW(e,t),RW(` `,t),LW(n)]));function HW(e,t,n,r){return t===void 0?RW(r):VW(r,void 0,t(n,e))}function UW(e,t,n,r,i){let a=MW(e.palette,i,r);return(e,r,i,o)=>RW(q.fromFragments([RW(o?`[`:` `,a),LW(n(r,t)),RW(o?`]`:` `,a)]))}function WW(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=>GW(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function GW(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function KW(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function qW(e){return{current:null,drawnAt:e}}function JW(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 YW(e,t,n){return ZW(e,()=>n(JW(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function XW(e,t){return ZW(e,()=>(e.current=null,t()))}function ZW(e,t){let n=e.current;try{return t()}finally{e.current=n}}function QW(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 $W(e){return new q(e).cellLength}function eG(e){let{width:t,chromeCols:n,padding:r}=pW(e,`a row fit`);return Math.max(1,t-n-2*r)}function tG(e){let{padding:t,seamCols:n}=pW(e,`a row fit`);return Math.max(1,eG(e)-($W(`✕`)+2*t+n))}function nG(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 rG(e,t,n){let r=$W(`←`)+1+$W(`→`)+1,i=nG(e,t,n);return(i.length>1?nG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function iG(e){let t=[];for(let n of e)t.length>0&&t.push(new q(` `)),t.push(n);let n=q.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function aG(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 oG(e,t,n){let r=e.compiled.get(t),i=r&&yW(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 sG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=pW(a,`picker`).store,d=SW(u,`session.id`),f=`stateVar`in t?SW(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?tG(a):eG(a):1/0,h=(r.kind===`led`?0:$W(`✕`)+1)+c.reduce((e,t)=>e+$W(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?rG(v.map(e=>e.cellLength),m,h):WW(g.entries,g.groups,i),b=parseInt(SW(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,ee=y[C]??[],w=e=>Ta([{verb:Wi,args:[d,n.key,String(e)]}]),te=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?te:[],T=e=>Ta([...DW(l,e,e,u,d,a.signer).effects,...ne]),re=(e,n)=>TW(e,T(t.options[n])),E=r.kind===`led`?[]:[wW(`✕`,Ta(te),!1,s)];E.push(...c.map(({glyph:e,option:r})=>wW(e,Ta([...DW(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&E.push(wW(`←`,w(C-1),!1));let D=C<y.length-1?[wW(`→`,w(C+1),!1)]:[];if(g===void 0){let e=ee.flatMap(e=>e.indices);return[iG([...E,...e.map(e=>re(v[e],e)),...D])]}let ie=new W({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=ee.length===1?[new q(`${ee[0].label}${O}`,{style:ie})]:[],oe=[iG([...E,...ae,...D])];for(let e of ee){ee.length>1&&oe.push(iG([new q(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>$W(_(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:NP(i),o=` `.repeat(n-$W(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(iG([re(p(r,KW(s,m)),r)]))}}return oe}function cG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{jA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=aG(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=oG(e,n,`picker`),u=QW(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=>sG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,BW(u,cv(void 0),mW(e,`{{ picker }}`),l.paletteOf,d,t),PW(u.palette,t,d)),p=Pv(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 lG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function uG(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=pW(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=SW(a,`session.id`),{options:c}=t;if(c.length===0)return iG([]);let l=lG(c,SW(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ta(DW(o,u(e),u(e),a,s,i.signer).effects);return iG([wW(`◀`,d(-1),!1),TW(HW(mW(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ta(DW(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),wW(`▶`,d(1),!1)])}function dG(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(bW(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 uG(t,oG(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function fG(e,t,n){let r=oG(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 pG(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function mG(e,t,n,r){let i=fG(e,t,n),a=r??SW(pW(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,mW(e,`{{ ${n} }}`))}function hG(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(jA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return LW(mG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function gG(e,t,n){return{swatches:{fn:(r,i)=>{let a=fG(e,r,`swatches`),o=aG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=QW(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]=sG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,UW(s,mW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),PW(s.palette,s.bg,c),u===0?[]:(()=>{let t=lG(l,SW(pW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[pG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const _G=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function vG(e,t,n,r){let i=Pv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:wv(e,n,r)});return[[J_(e,t,r).map((n,i)=>{let a=Sv(e,n);return{text:_G[i%_G.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 yG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new q(` ${e} `,{style:NW({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 q(e)),r.push(a)}return r}function bG(e,t,n,r,i){let a=vG(e,t,n,r).map(e=>yG(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
|
|
181
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
182
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
176
|
+
`,mP=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function hP(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function gP(e,t,n){return T.resolve(e,hP(t,n))}function _P(e,t,n){return typeof t==`string`&&t!==``?gP(e,t,n):void 0}const vP=`CC_CANDYBAR_CONFIG`;function yP({env:e,home:t},n){return _P(n,e[vP],t)}function bP(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function xP(e,t,n){return bP(_P(n,e,t.home),yP(t,n))}function SP(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const CP=new Ff({"strip.separator":`default`,"strip.rail":`default`});function wP(e){return CP.resolve(e)}const TP={kind:`still`},ote=e=>Pp.at(e.timeline,e.wall),EP=Symbol(`bar`);function ste(e){return e.name!==ly}function cte(e){return t=>K.map(K.all(e.map(({timeline:e,effect:n})=>Pp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const DP=wee;function lte(e,t){let n=new vu(t,DP.foregroundColor,DP.ansiColors,DP.palette);return t=>e({...t,theme:n})}function ute(e,t){return n=>wh(()=>e(n),...t)(n)}function OP(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 kP=4096;function dte(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=mx.reduceRight((e,{lit:t,seconds:n})=>K.sequence(K.constant(t?r:i),n,e),K.constant(i)),o=K.sequence(K.constant(i),n,a);return()=>o}var AP=class{inForce=null;anchor=Pp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:ly,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:Pp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=ote(t),a=e=>Pp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:EP,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=Hg.transitions[e]({z:OP(`${this.key}@${t}`)*kP});return{name:e,since:i,done:e=>r.done(e),effect:lte(r.effect,n)}},C=({since:e,done:t})=>t(i-e),ee=(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}),w=(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)}},te=(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?w(e,r):ee(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)},ne=(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}},T=(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=OP(t.scope===EP?e:`${e}@${t.scope}`),s=a?i.effect:Hg.loops[t.name]({z:o*kP});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},re=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ne(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()]},E=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:wh(n.effect,...t)}]})},D=r===null?[]:[{timeline:Pp.play(r.idleSince),effect:dte(r.fill,r.text,Hee(r.timeoutS))}],ie=e=>e===`menu`?D:[];return{placed:h===`off`?(e,t)=>t:te,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?re(r):[{...s,owners:void 0}]).filter(ste),o=E(r),c=ie(n);if(i.length===0&&o.length===0&&c.length===0)return TP;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new yh(e,cte([...i.map(e=>{let t=T(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:ute(t,e.owners)}}),...o,...c]),{key:l,theme:DP})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},fte=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new AP(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 jP={fg:`#ffffff`,bg:`#c82828`},MP={fg:`#000000`,bg:`#dca028`};function NP(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const pte=NP(38,jP.fg),mte=NP(48,jP.bg),hte=[[0,31],[127,159],[8234,8238],[8294,8303]];function gte(e){return hte.some(([t,n])=>e>=t&&e<=n)}function PP(e){let t=``;for(let n of e)t+=gte(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function FP(e,t){let n=PP(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const _te=`${mte}${pte}`;function IP(e){return`⚠ cc-candybar: ${yte(e)}`}function vte(e){return`${_te}${IP(e)}[0m\n`}function yte(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: ${FP(e.message,60)}`;case`render_failed`:return`render failed: ${FP(e.message,60)}`;case`switched_off`:return`switched off: ${FP(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${FP(e.message,60)}`}}function LP(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function RP(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:PP(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function bte(e){return RP(IP({kind:`permanent`,cause:`render_failed`,message:e}),jP)}function zP(e,t){try{return e(t)}catch(t){return e(RP(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,jP))}}function BP(e){return e.type===H.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const xte=Object.keys(new W().attributes);function Ste(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=xte.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:BP(n)},...r!==void 0&&{bg:BP(r)},...i.length>0&&{attrs:i}}}function Cte({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&Ste(t,n),...t?.link!==void 0&&{link:t.link}}}function wte(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return G.splitLines(n).map(e=>e.map(e=>Cte(e,t)))}function Tte({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new G(e,new W({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function VP(e,t){let n=Yl(t);return e.map(e=>jee(e.map(Tte),n)).join(`
|
|
177
|
+
`)}function HP(e){return VP(e.rows.map(e=>e.runs),e.depth)}function Ete(e){return HP(e)+`
|
|
178
|
+
`}const Dte=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function UP({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&Dte(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function WP(e){return e.map(e=>e.text).join(``)}const Ote={};function GP(e,t){let n=Yl(t.colorSystem),{time:r}=t,i=1/0,a=[...op(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:CP,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:Ote}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:wte(a,n.colorSystem),nextChange:Math.min(G.nextChange(a),i)}}const KP=new Map;function kte(e){let t=KP.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}=vh.plain,a=new Hm({glyph:n(r.glyph),ascii:r.ascii},i);return KP.set(e,a),a}function qP(e,t){return e===`plain`&&t!==void 0?kte(t):vh[e]}const JP=new Map;function YP(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=JP.get(t);if(n!==void 0)return n;let r=qP(e.endcaps,e.separator),i=e=>new q(`x`,{end:``,overflow:`ignore`,style:new W({bgcolor:e})}),a=e=>{let{lines:t}=GP(new dm(e,r),{colorSystem:null});return new q(WP(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return JP.set(t,s),s}function XP(e){return YP(e).chrome}function ZP(e){return YP(e).seam}const Ate=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function QP(e){return[...new Set(e.match(Ate)??[])].join(``)}function jte(e){let t=qP(e.endcaps,e.separator),n=e=>new q(`x`,{end:``,style:new W({bgcolor:e})}),{lines:r}=GP(new dm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return QP(WP(r.flat()))}function $P(e){return e.wrap?e.width:1/0}function Mte(e,t){return GP(new q(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(WP)}function eF(e,t,n=TP){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=qP(t.endcaps,t.separator),i=Number.isFinite($P(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new x_([...e],{joiner:r}):new dm([...e],r),s=n.kind===`still`?GP(o,a):GP(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function Nte(e,t){return VP(eF(e,t).lines,t.colorCompatibility)}const Pte=[`moves`,`can-move`,`still`];function tF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const Fte=[`statusline`,`frames`],nF=e=>e?.kind===`frames`?`frames`:`statusline`,Ite=[`carried`,`missing`,`unanswered`];function Lte(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:tF(e)===`no`?`unanswered`:`missing`}function Rte(e){return{path:e.transcript_path,answered:tF(e)===`yes`}}const rF=[...Pte,`failed`,`drawing`];var zte=class{seen=new Map;see(e,t,n,r){let i=nF(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 iF={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`}}},aF=e=>iF[e];function Bte(e){return aF(e).glyphs.kind===`bundled`}function Vte(e){return aF(e).glyphs.kind===`configured`}const oF=e=>aF(e).label,Hte=[{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 Ute(e,t){let n=t.codePointAt(0);return Hte.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&lF(e,t)===!0)}const sF=Object.keys(iF);function cF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function lF(e,t){let n=cF(e),r=cF(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 Wte(e){for(let t of sF){let n=aF(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 uF(e){let t=sF.find(t=>aF(t).term===e);return t===void 0?null:{name:t,version:null}}function Gte(e){let t=Wte(e.termtype)??uF(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 Kte(e){let t=e.TERM_PROGRAM,n=sF.find(e=>aF(e).program===t),r=n===void 0?uF(e.TERM):{name:n,version:aF(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 dF(e){switch(e.kind){case`known`:return oF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function fF(e){switch(e.kind){case`known`:return oF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function qte({name:e,version:t}){let n=aF(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=lF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Jte=sF.filter(e=>aF(e).links!==null).map(oF).join(`, `);function pF(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(!us(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||!us(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function mF(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 Yte=[`managed`,`project`],Xte=e=>!Yte.includes(e.scope),Zte={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:ss(t.projectDir)}),user:e=>({scope:`user`,path:e})},hF=[`drawn`,`boxes`],gF=1024*1024,_F=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function Qte(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 vF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const yF=Uc.truecolor;function bF(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 $te={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>bF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=mF(t.sources,yF);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:`${yF} 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`,yF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Zte[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 ${yF} to "1" there`}:o(s)})},ene={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>bF(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"})},tne={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:`${_F(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 ${_F(e.value.of)} measured`}},nne={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},rne={argument:`command argument`,environment:`$${vP}`,unknown:`source unknown`};function ine({target:e,layers:t}){return e.source===`search`?t.length===0?SP(t):`${SP(t)} (searched)`:`${e.path} (${rne[e.source]})`}function ane(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}" ${nne[e]}`)]}}const one={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=ine(e),n=vF(ane(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},xF="re-run `cc-candybar install`";function sne(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:// — ${xF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${xF}`]}const cne={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 — ${xF}`};case`lost`:return vF([...sne(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 SF({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 CF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${ix.join(`|`)}>\``:e.checkout===null?xF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function lne(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 — ${CF(e,`native`)}`];let{bundle:i,source:a}=SF(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} — ${CF(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 — ${CF(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 wF=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)`},une={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`:`${wF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:vF([...new Set(i.flatMap(e=>lne(n,r,e)))])}};function TF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||zr(e.identity,t.value.through)):[]}function EF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const dne={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`?EF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return vF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=TF(e.value,n),u=vF([...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 ${Ir(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 ${Ir(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Hr(o.charge.bytes,s)?[`the daemon holds ${Kr(o.charge)} of its ${Ir(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}}}},DF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function OF(e,t){let n=dF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?qte(e.terminal):{kind:`unknown`}}function kF({identified:e,tmuxClient:t},n){let r=fF(e),i=OF(e,n),a=dF(e)===null?DF:`${DF}, 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: ${Jte}`];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 AF={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 vF(kF(t,n))}}},jF=e=>e.filter(e=>e.role===`statusline`),MF={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})=>FF(e,NF(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:PF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:wF(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}}},NF=e=>{let t=jF(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, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},PF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function FF(e,t){let n=pF(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 PF(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 Xte(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 IF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function LF(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return fF(e);case`bundling`:case`unread`:case`configured`:return[oF(e.name),e.version].filter(e=>e!==null).join(` `)}}function RF(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return dF(e);case`bundling`:case`unread`:return oF(e.name);case`configured`:{let t=oF(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 zF(e){let t=RF(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${IF(e.glyphs)}`}}const BF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=zF(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=LF(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 ${IF(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=iF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:lF(i.version,e);if(t===!0)return{ok:!0};let n=oF(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 ${IF(n)} — set a Nerd Font as its font`)}}}};function VF(e){return e.join(`, `)}function HF(e){return`or set missingData: "ignore" on ${VF(e)}`}function UF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${VF(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`?[`${VF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${HF(t)}`]:[`${VF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${HF(t)}`]}function WF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${VF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${VF(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`:`${VF(n)}: ${wF(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`)?[`${VF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${VF(n)}`]:[]}const GF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>vF([...UF(e.pullRequests),...WF(e.rateLimits,t)])};function KF({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 ${gF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const qF=[one,une,dne,cne,AF,$te,ene,tne,MF,BF,GF,{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`:`${wF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:vF(e.value.flatMap(KF))}],JF=qF.filter(e=>e.takesMark);function YF(e){return qF.map(t=>({check:t,verdict:t.probe(e)}))}function XF(e){return qF.find(t=>t.name===e)}const ZF=`${F}doctor.`;function QF(e){let t=`${ZF}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function $F({target:e}){return`configTarget=${e.source}`}function eI(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?dF(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 tI(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 nI(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}=SF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const rI=e=>`${e>=0?`+`:``}${Ir(e)}`;function iI({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${EF(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`:`${TF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${qr(i.charge)}${i.charge.kind===`stand-in`?`(${rI(-i.charge.gap)})`:``}:${Ir(i.charge.bytes)}`}/${Ir(a)} postMortems=${s}`}function aI(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 oI(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>sI(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=jF(r.flatMap(e=>e.bars));return`frames=${rF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function sI(e){let t=pF(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 cI(e){let t=mF(e,yF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function lI(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 uI(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=zF(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 dI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function fI(e){return e.flatMap(({check:e,verdict:t})=>{let n=QF(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Oy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:dI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Oy:Dy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const pI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function mI(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(pI).map(([t,n])=>[`${e}${t}`,n]))}}const hI=`armed`,gI=`disarmed`,_I=`.armed`,vI=e=>e.endsWith(_I);function yI(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 bI(e,t,n){let r=`${e}${_I}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${hI}")`,s=yI(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:hI},[a]:{set:r,to:gI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:gI}},disarm:a}}const xI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function SI(e){return typeof e==`string`&&xI.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 CI(e){let t=SI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const wI=[`/compact`,`/model`],TI=`/clear`;function EI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=bI(`${e}clear`,{arm:TI,confirm:`${TI} ✓ confirm`},[{action:n,when:`true`}]);return{template:wI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${nx} }}`,actions:{...Object.fromEntries(wI.map(e=>[t(e),{slash:CI(e)}])),...r.actions,[n]:{slash:CI(TI)}},variables:r.variables,disarm:r.disarm}}const DI=Array.from({length:10},(e,t)=>(t+1)*1e5),OI=DI[0],kI=DI[DI.length-1];function AI(e){let t=is(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?I(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=OI&&n<=kI?I(n):R(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${OI}–${kI} tokens)`,`parse`)}function jI(e,t){let n=Math.min(t??kI,kI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:DI.filter(e=>e<r).at(-1)??0,higher:DI.find(e=>e>r&&e<=n)??0}}function MI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${nx} }}{{ 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:CI(`/autocompact auto`)},...Object.fromEntries(DI.map(t=>[`${e}${t}`,{slash:CI(`/autocompact ${t}`)}]))}}}const NI=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 }}`,PI=`${F}edit`,FI=`${F}toolbar`,II=mI(F),LI=`${F}commands`,RI=EI(`${LI}.`),zI=`${F}autocompact`,BI=MI(`${zI}.`,NI),VI=e=>({kind:`segment`,name:e}),HI=`${F}tab`,UI=e=>`${HI}.${e}`,WI=e=>`${UI(e)}.toggle`,GI=e=>({variable:HI,key:HI,member:e}),KI=`${F}save`,qI=`${F}preset.save`,JI=`${F}preset.delete`,YI=e=>`${F}${e}`,XI=e=>`${F}apply.${e}`,ZI=e=>`${F}reset.${e}`,QI=`${F}themeDefault.save`,$I=`${F}themeDefault.differs`,eL=`${F}themeDefault.theme`,tL={when:`{{ .${$I} }}`,template:`{{ action "${QI}" (printf "⤓ default for %s" .${eL}) }} {{ swatch "${XI(`theme`)}" .${eL} }}`},nL=`${F}resetAll`,rL=`${Li}.toggle`,iL=`${F}undo`,aL=`${F}back`,oL=`${aL}.step`,sL=`${F}navigation.back`,cL=aL,lL={template:`{{ if gt .${sL} 0 }}{{ action "${aL}" "◁" }}{{ else }}{{ fg (${mP}) "◁" }}{{ end }}`},uL=`${F}redo`,dL=`${F}doctor`,fL=`${dL}.run`,pL=e=>`${dL}.fix.${e}`,mL=(e,t)=>`${dL}.mark.${e}.${t}`,hL=e=>`${dL}.${e}`,gL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},_L=DM(`${F}pickers`),vL=e=>`${F}${e}`,yL=e=>`${vL(e)}.toggle`,bL=e=>KM(e)?DM(`${F}${e}Pickers`):_L,xL=e=>{let t=bL(GM[UM[e].beside]);return{variable:t,key:t,member:e}},SL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${JI}" (printf "🚮 delete %s" .${Fx.preset.effectiveVar}) }}`}},CL=(e,t)=>`${F}list.${e}.${t}`,wL=e=>`${F}resettable.${e}`,TL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${wL(e.name)})`).join(` `)})`,EL=ix.map(e=>[rx[e].switch.setting,e]),DL={variables:{},actions:{},segments:{}},OL=Object.fromEntries(EL.map(([e,t])=>[e,$N(`${F}help.${e}`,fP[t],[],DL)])),kL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],AL=e=>{let t=t=>`.${lx(e,t)}`,n=kL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Fx[rx[e].switch.setting].effectiveVar} ${JSON.stringify(rx[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},jL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${Bi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,ML=`${F}fps`,NL=`{{ if eq .${sx(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${sx(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,PL=Object.fromEntries(EL.map(([e,t])=>[e,AL(t)])),FL=e=>WM.filter(t=>UM[t].beside===e),IL=Object.keys(Fx).map(e=>{let t=Fx[e],n=GM[e];return{...t,name:e,place:n,control:zM({label:t.label,domain:$M(t.configKey)},t.sessionKey,t.effectiveVar,XI(e),bL(n)),beneath:t.previews.map(e=>SL[e]),help:[OL[e]].filter(e=>e!==void 0),submenus:FL(e)}}),LL=e=>IL.filter(t=>t.place===e),RL=e=>IL.filter(t=>qM(t.place,e)),zL=e=>t=>`(print ${Di(t)} (ternary ${Di(` •`)} "" ${TL(RL(e))}))`,BL=e=>LL(e).flatMap(e=>[QL(e),...e.help,...e.submenus.map(e=>Si(vL(e),xL(e),aR(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(IL.flatMap(e=>[e.sessionKey,e.configKey]));const VL=bI(nL,{arm:`⟲`,confirm:`⟲ reset all?`},IL.map(e=>({action:ZI(e.name),when:e.shown}))),HL=[`unsaved`,`history.undo`,`history.redo`],UL=e=>`${F}${e}`,WL=UL(`unsaved`),GL=(e,t)=>({body:t,shown:`(gt .${UL(e)} 0)`}),KL=[GL(`unsaved`,`{{ action "${KI}" (printf "💾 save %d" .${WL}) }}`),GL(`history.undo`,`{{ action "${iL}" "↶" }}`),GL(`history.redo`,`{{ action "${uL}" "↷" }}`),{body:VL.template,shown:`(or ${TL(IL)} ${VL.armed})`}],qL={when:`{{ or ${KL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+KL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},JL=[{step:VL,place:`door`},{step:RI,place:`session`}],YL=e=>e.map(e=>e.step.disarm),XL=YL(JL),ZL=YL(JL.filter(e=>e.place!==`door`));function QL(e){let t=YI(e.name);return e.control.kind===`inline`?VI(t):Si(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>VI(CL(e.name,n)))},`drop`)}function $L(e){return e===Li}function eR(e){let t=VI(Li);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[eR(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 tR(e){return nR(e)>0?e:eR(e)}function nR(e){let t=0;for(let n of zy(e))n.kind===`segment`&&$L(n.name)&&(t+=1);return t}function rR(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&$L(e.name)||e.opens!==void 0&&rR(e.opens.body,!0):e.children.some(e=>rR(e,n))}const iR={door:{direction:`horizontal`,content:[VI(cL)],after:[VI(PI),VI(KI)]},session:{direction:`vertical`,content:[VI(FI),{kind:`container`,direction:`horizontal`,children:[VI(LI),VI(zI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[VI(qI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[VI(dL),...qF.map(e=>VI(hL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[VI(QI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function aR(e){let{direction:t,content:n,after:r}=iR[e];return{kind:`container`,direction:t,children:[...n,...BL(e),...r]}}function oR(e){return e.kind===`segment`?$L(e.name)?{kind:`container`,direction:`horizontal`,children:[Si(e.name,zi,cR,`above`),VI(ML)]}:e:lR(e)}function sR(){return{kind:`container`,direction:`vertical`,children:[aR(`door`),{kind:`container`,direction:`horizontal`,children:VM.map(({member:e})=>Si(UI(e),GI(e),aR(e),`drop`))}]}}const cR=sR();function lR(e){return{...e,children:e.children.map(e=>oR(e))}}function uR(e){let t={variables:{[Li]:Oi(Li,P),[Bi]:{kind:`state`,key:Bi,default:`0`}},actions:{[rL]:ki(Li,Ri),[Bi]:{set:Bi,int:!0},[Li]:{do:[rL,...XL]},[fL]:{doctor:`run`},...II.actions,...RI.actions,...BI.actions,[KI]:{save:!0},[iL]:{undo:!0},[oL]:{back:!0},[aL]:{do:[oL,...XL]},[uL]:{redo:!0},[qI]:{preset:`save`},[QI]:{themeDefault:`save`},[JI]:{preset:`delete`,name:`{{ .${Fx.preset.effectiveVar} }}`}},segments:{[Li]:{template:`{{ $door := ${Ei(Li,Di(e),Di(`✖`))} }}{{ if ${wi(zi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+jL},[ML]:{template:NL},[FI]:{template:II.template},[LI]:{template:RI.template,when:RI.when},[zI]:{template:BI.template,bg:BI.bg,when:BI.when},[cL]:lL,[KI]:qL,[QI]:tL,[qI]:{template:`{{ action "${qI}" "+ preset" }}`},[dL]:{template:`{{ action "${fL}" "🩺 doctor" }}`},[PI]:{template:`{{ action "${UN}" "✎ arrange" "✎ done" }}`}}};t.variables[$I]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[eL]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[sL]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of HL)t.variables[UL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[HI]=Oi(HI,P);for(let{member:e,label:n}of VM){t.actions[WI(e)]=ki(HI,e),t.actions[UI(e)]={do:[WI(e),...ZL]};let r=zL(e);t.segments[UI(e)]={template:`{{ ${Ei(UI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,RI.variables,VL.variables),fR(t),dR(t),t}function dR(e){for(let t of qF){let n=QF(t.name),r=pL(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?hF:[];for(let n of i)e.actions[mL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${mL(t.name,e)}" "${gL[e]}" }}`).join(``);e.segments[hL(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} "${Dy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function fR(e){for(let t of IL){Object.assign(e.actions,t.control.actions);let n=ZI(t.name);e.actions[n]={reset:t.configKey},e.variables[wL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${wL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[YI(t.name)]={template:`${t.control.template}${PL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[CL(t.name,r)]=n})}Object.assign(e.actions,VL.actions),Object.assign(e.variables,DL.variables),Object.assign(e.actions,DL.actions),Object.assign(e.segments,DL.segments);for(let t of WM){let n=xL(t);e.actions[yL(t)]=ki(n.key,n.member),e.segments[vL(t)]={template:`{{ action "${yL(t)}" ${zL(t)(UM[t].trigger)} }}`}}}function pR(e){let{variables:t,actions:n}=QN();Object.assign(e.variables,t),Object.assign(e.actions,n)}function mR(e){let t=uR(e.globals.menuGlyph??`🍫`);pR(t);let n={...e.presets},r=[];for(let t of pS(e.presets)){let{node:i}=gS(e,t),a=oR(tR(i));r.push(a),n[t]={...hS(e.presets,t),root:a}}let i=CM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const hR=`${Pi}live`,gR=[`☐ live`,`☑ live`],_R=`${Pi}done`,vR=`${Pi}cancel`,yR=`${Pi}rewind`,bR=`${Pi}changes`,xR=`(gt .${bR} 0)`,SR=`(or ${xR} (gt .${WL} 0))`,CR={variable:hR,key:hR,member:_i};function wR(e){return`${Pi}configuring.p${e}`}function TR(e){return`and ${wi(qN)} (not ${wi(CR)}) (ne .${wR(e)} "true")`}function ER(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${HN} "${xi(e)}")`).join(` `)} false }}`}}function DR(e,t,n){return`{{ if ${TR(e)} }}${t}{{ else }}${n}{{ end }}`}const OR=`{{ and ${wi(qN)} .preset.customized }}`,kR=Ii;function AR(e){return new Map([...CS(e),...MR(e)])}const jR=`${Pi}addable`;function MR(e){return new Map([[jR,{members:Object.keys(e.segments).filter(e=>!kR(e)),library:{groups:FN.map(e=>({id:e,label:IN[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function NR(e,t,n){return n.segments[e]={template:t,when:JN,bg:tP},{kind:`segment`,name:e}}function PR(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) ${Cv}`}) (action "${r}" "✖") }}`}function FR(e){return`{{ if ${wi(qN)} }}${e}{{ end }}`}function IR(e,t){return e.reduce((e,t)=>`{{ if and ${wi(qN)} ${wi(t)} }}true{{ else }}${e}{{ end }}`,t)}function LR(e){return e.flatMap(e=>[...zy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function RR(e,t,n){return`${GN}${e}.${t}.${n}`}function zR(e,t,n,r){let i=Fy(n),a=`${Pi}${e.presetIdent}`,o=KN(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=DM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:HN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=RR(e.presetIdent,i,r),l=`${GN}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:ab(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=zM(LM(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}" "${sP}" }}`,ref:{variable:HN,key:HN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const BR=`${Pi}label:`;function VR(e){if(e.startsWith(BR)){let t=e.slice(BR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function HR(e,t,n,r){let i=Fy(e),a=UR(n,i,e,t,i),o=Object.fromEntries(eb.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Si(a,r.ref,r.body,`drop`,IR([r.ref],`{{ ${TR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(eb.map(e=>[e,r.drafts[e]]))}}function UR(e,t,n,r,i){let a=`${BR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${xi(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function WR(e,t,n,r){let i=Fy(e),a=n?[qR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=qR(r,o,i,`after`),c=PR(r,o,i),l=r.segments[e.name],u=zR(r,o,e,tb(l)),d=FR(c),f=FR(u.term);return[...a.map(e=>NR(e.host,e.template,r.artifacts)),{...HR(e,l,r,u),lead:d,trail:f},{...t,when:DR(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},NR(s.host,s.template,r.artifacts)]}function GR(e){return T.join(T.basename(T.dirname(e)),T.basename(e))}function KR(e,t,n,r){let i=r.segments[e.name],a=Fy(e);return[{kind:`segment`,name:UR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${GR(t.file)} ${t.entry}`),when:`{{ ${TR(r.presetIdent)} }}`},{...n,when:DR(r.presetIdent,`false`,e.when??`true`)}]}function qR(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:jR,anchor:n,relation:r};let c=TM(o),l=EM(s,o,void 0),u=kM(l),d=OM(l,c);return a.variables[l]={...Oi(l,P),within:[qN]},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) ${Cv}`}) $m }}{{ end }}`}}function JR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!kR(e.name)&&e.insertedBy===void 0),i=e=>JR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Ry(o,i);if(kR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?WR(o,s,a===r,t):KR(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:IR(LR(n),DR(t.presetIdent,`true`,e.when))}}}function YR(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:OR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},XR(e,o)]}}function XR(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),XR(n,t)]}:{...e,children:[...e.children,t]}}function ZR(e,t,n,r,i,a){let{node:o}=gS(e,t),s={presetIdent:wM(t),rootKey:ON(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=JR(o,s);return n.variables[wR(s.presetIdent)]=ER(s.configured),YR(c,s.presetIdent,s.rootKey,n,r,i,a)}function QR(e){let t={variables:{},actions:{},segments:{}},n=$N(`${Pi}help`,dP,[qN],t);t.variables[hR]=Oi(hR,P),t.actions[hR]=ki(hR,CR.member),t.segments[hR]={template:Ti(hR,...gR),when:JN};let r={kind:`segment`,name:hR},i=n;t.variables[bR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[_R]={do:[KI,UN]},t.segments[_R]={template:`{{ if ${SR} }}{{ action "${_R}" "✓ save" }}{{ else }}{{ action "${_R}" "✓ done" }}{{ end }}`,when:JN},t.actions[yR]={rewind:!0},t.actions[vR]={do:[yR,UN]},t.segments[vR]={template:`{{ action "${vR}" "↩ cancel" }}`,when:`{{ and ${wi(qN)} ${xR} }}`};let a=[{kind:`segment`,name:_R},{kind:`segment`,name:vR}],o={...e.presets},s=[];for(let n of pS(e.presets)){let c=ZR(e,n,t,a,r,i);s.push(c),o[n]={...hS(e.presets,n),root:c}}let c=CM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function $R(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function ez(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 tz(e,t,n){let r=Ly(e,new Set(n.map(Iy).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const nz=/^-?\d+$/;function rz(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 iz(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!nz.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 az(e,t,n){return r=>r?nz.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 oz(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=>!nz.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 sz(e){return e===`config`?`set-config`:`set-state`}function cz(e,t,n){return t.kind===`int`?iz(`menu page "${e}"`):t.kind===`range`?az(t.min,t.max,`${n} stepper "${e}"`):rz(t.allowed,`${n} "${e}"`,sz(n))}function lz(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:oz(e,n,t)}))}function uz(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 lz(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,cz(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 dz(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};uz(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=uz(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function fz(){return dz({},`config`,gz)}function pz(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:[$R({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[$R({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=>$R({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function mz(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?MN(n.persist):null;e?.scope===`preset-root`&&t.add(ON(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function hz(e){let t=AR(e);return[...mz(e),...Object.values(e.actions).flatMap(e=>pz(e,t))]}function gz(e){return lz(hz(e),`config`)}const _z=Zv(),vz=new Set(_z),yz=new Set(yy),bz=e=>e?vz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${_z.join(`, `)})`}:{ok:!1,reason:`theme name is required`},xz=e=>e?yz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${yy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},Sz=new Set([`1`,`true`]),Cz=new Set([`0`,`false`]),wz={endcaps:xz,theme:bz,"toolbar-expanded":e=>Sz.has(e)?{ok:!0,value:`1`}:Cz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function Tz(){return dz(wz,`state`,kz)}function Ez(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 Dz(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(wz,e.key))}function Oz(e){let t=AR(e);return Dz(Object.values(e.actions).flatMap(e=>Ez(e,t)))}function kz(e){return lz(Oz(e))}function Az(e){let t=Tz(),n=fz();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 jz=`update.dismissed`,Mz=`updateNotice`,Nz=Fx.updateNotice.sessionKey;function Pz(){return Az({config:[{key:Mz,allowed:[`false`]}],state:[{key:Nz,allowed:[`false`]},{key:jz,allowed:[]}]})}function Fz(e){try{return s.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Iz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:zz(t.segments,Lz(t.segments,e.segments??{})),root:iS(e.root??Qx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:zz(t.presets,Rz(t.presets,e.presets??{})),themeDefaults:zz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Lz(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 Rz(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 zz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Bz=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 Vz(e){let t=Bz.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 Hz(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: ${Gy.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Gz(e,`${t}.cache`,n.cache)}function Uz(e){return{required:!0,json:Kz(),parse:(t,n,r,i)=>Hz(t,n,i,e)??void 0}}const Wz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Jz(n)?{ttl:n}:Fb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${kb(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Fb(e,t,`cache.watch_file must be a path string, got ${kb(n)}`);let r=qb(`cache.watch_file`,n);return r===null?{watch_file:n}:Fb(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}:Fb(e,t,`cache.depends_on must be an array of variable-name strings, got ${kb(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Fb(e,t,`cache.key must be a non-empty template string, got ${kb(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Fb(e,t,`cache.never must be the literal boolean true, got ${kb(n)}`)}}};function Gz(e,t,n){return Ib(e,Wz,t,n)}function Kz(){return ex(Wz)}const qz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Jz(e){return qz.test(e)}const Yz=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 Xz(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 Zz(e){let t=Yz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Xz(t)}`}function Qz(e){let t=Yz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Xz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const $z=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`]]),eB=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 tB(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 nB(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`?eB.get(e.field):void 0;if(n===void 0){let e=[...eB.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 ${tB(n.declare)} under a name of your own`}const rB=new Map([[`HOME`,`home`],[`USER`,`host.user`],[`LOGNAME`,`host.user`],[`HOSTNAME`,`host.name`]].map(([e,t])=>[e,{read:`.${t}`,declare:{kind:`input`,path:t,default:``}}]));function iB(e){let t=`kind "env" is removed${typeof e.name==`string`?` (this one read $${e.name})`:``}: the renderer's environment belongs to whichever shell spawned it, not to the session it draws for, so an env variable was never a session fact — drop this declaration`,n=typeof e.name==`string`?rB.get(e.name):void 0;return n===void 0?`${t}; a value the payload lacks is read from a file by a "file" source or computed by a "shell" source, and not by echoing the variable there, since a "shell" source runs in the renderer too`:`${t} and read ${n.read} where it was read, or declare ${tB(n.declare)} under a name of your own`}const aB=new Map([[`load-config`,`the load-config verb is removed — a session's config is the file its statusline command names with --config, else the file its shell names in $${vP}; point the session there instead of linking to a path`]]);function oB(e){let t=aB.get(e);return t===void 0?void 0:`Template spells "${Vi}://${e}/…", a URL no click runs: ${t}`}function sB(e,t,n){if(n===void 0)return{};if(!Db(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Ob(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Lb(e,kB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function cB(){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 ${Ob(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function lB(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Cb(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const uB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Fb(e,t,`parse.text must be the literal boolean true, got ${kb(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?dB(e,t,n):Fb(e,t,`parse.regex must be a pattern string, got ${kb(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Fb(e,t,`parse.json must be the literal boolean true, got ${kb(n)}`)}}};function dB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Fb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Fb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function fB(){return{required:!1,json:ex(uB),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:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ib(e,uB,`${t}.parse`,r.parse)??void 0)}}function pB(){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)=>Db(r.parse)&&`json`in r.parse?mB(e,t,r.default):wb(e,t,r,`default`)}}function mB(e,t,n){if(n!==void 0)return hB(n)?n:Fb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${kb(n)}`)??void 0}function hB(e){return e!==null&&wC(e)}const gB={value:cB(),default:Vb()};function _B(){let e=Kb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:$z.get(a);return o===void 0?a:Fb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const vB={path:_B(),type:Yb([`string`,`number`,`boolean`]),default:lB()},yB={path:Jb(),readMode:Yb([`whole`,`first-line`]),parse:fB(),cache:Uz(`file`),default:pB()},bB={command:Kb(),parse:fB(),cache:Uz(`shell`),default:pB()};function xB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const SB={template:Kb(),type:Yb([`string`,`number`,`boolean`]),default:lB()},CB=xB(`a template variable recomputes whenever a variable it reads changes`),wB={layout:Kb(),default:Vb()},TB=xB(`a time variable reads the instant its render is drawn at`),EB={key:Kb(),default:Vb()},DB=`kind`;function OB(e,t,n={}){return{...Rb(DB,e,t),parse:(r,i,a)=>{jb(r,n,i,a);let o=Mb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const kB={tag:DB,noun:`source kind`,memberNoun:`variable`,arms:{literal:OB(`literal`,gB),input:OB(`input`,vB),file:OB(`file`,yB),shell:OB(`shell`,bB),template:OB(`template`,SB,CB),time:OB(`time`,wB,TB),state:OB(`state`,EB)},retired:{git:nB,env:iB}};function AB(){return $b(kB)}function jB(){return{type:`object`,additionalProperties:AB()}}const MB=/^[A-Za-z_][A-Za-z0-9_]*$/,NB={pattern:MB.source},PB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},FB={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`,...NB}}}]},default:PB}},IB=[`label`,`domain`,`default`],LB=[`min`,`max`,`step`,`atLeast`];function RB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function zB(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 RB(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 RB(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?RB(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(Db(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!LB.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}}:RB(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 RB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${kb(n)}`)}function BB(e,t,n){if(!Db(n))return RB(e,t,`${t} must be { label, domain, default }, got ${Ob(n)}`);for(let r of Object.keys(n))IB.includes(r)||RB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${IB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||RB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${kb(r)}`);let a=zB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!VB(n.default)||!ib(o,n.default)?RB(e,`${t}.default`,`default must be ${cb(o)}, got ${kb(n.default)}`):o}function VB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const HB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Qy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function UB(e){return eb.includes(e)}function WB(){return{required:!1,json:{type:`object`,propertyNames:{...NB,not:{enum:[...eb]}},additionalProperties:FB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Db(i))return RB(e,a,`${a} must be an object of name → { label, domain, default }, got ${Ob(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!MB.test(t)){RB(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(UB(t)){RB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${HB[t]}`);continue}let r=BB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const GB=Fi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function KB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${GB})[^:/]+$`},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:RB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Fi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${kb(i)}`)}}}function qB(){return{required:!1,json:{type:`object`,propertyNames:NB,additionalProperties:PB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Db(i))return RB(e,a,`a placement's "settings" must be an object of setting name → value, got ${Ob(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))VB(n)?o[t]=n:RB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Ob(n)}`);return o}}}function JB(e){return new Set(Object.keys(e.segments).filter(e=>!Ii(e)))}function YB(e,t,n){if(t===void 0)return{};if(!Db(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Ob(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Ab(e,n.has(i)?aV:iV,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function XB(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 ${Ob(s)}`,line:J(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 ${Ob(i)}`,line:J(e.source,[...t.split(`.`),n])})}const ZB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function QB(){return{required:!0,json:ZB,parse:(e,t,n,r)=>r[n]===void 0?Fb(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${Vz(t.slice(9))}`)??void 0:XB(e,t,n,r)}}function $B(){return{required:!1,json:ZB,parse:(e,t,n,r)=>r[n]===void 0?void 0:XB(e,t,n,r)}}function eV(){return{required:!1,json:{type:`object`,additionalProperties:ZB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Db(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${Ob(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=XB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function tV(){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 ${kb(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function nV(){return{required:!1,json:jB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return sB(e,`${t}.${n}`,i)}}}const rV={template:QB(),description:Vb(),group:Yb(PN),width:tV(),justify:Yb(lb),truncate:Yb(ub),bg:Vb(),fg:Vb(),when:Vb(),palette:Gb(),vars:nV(),settings:WB(),missingData:Yb(Yy),partials:eV()},iV={noun:`segment key`,fields:rV},aV={noun:`segment key`,fields:{...rV,template:$B()}};function oV(e,t){if(t===void 0)return{};if(!Db(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Ob(t)}`,line:J(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 ${kb(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function sV(e,t,n){if(t===void 0)return{};if(!Db(t))return X(e,`actions`,`actions must be an object, got ${Ob(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=cV(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function X(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function cV(e,t,n,r){if(!Db(n))return X(e,t,`${t} must be an action object, got ${Ob(n)}`),null;if(`persistWhen`in n)return X(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=OS.filter(e=>e in n);return i.length===1?uV(r)[i[0]](e,t,n):(X(e,t,`action must declare exactly one of: ${OS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function lV(e){return e===`<default>`?{dir:null}:T.isAbsolute(e)?{dir:T.dirname(e)}:{text:e}}const uV=e=>({set:(e,t,n)=>KV(e,t,n,`set`,HV),persist:(e,t,n)=>KV(e,t,n,`persist`,UV),copy:dV(`copy`),open:dV(`open`),reset:fV,undo:mV(`undo`),redo:mV(`redo`),back:mV(`back`),rewind:mV(`rewind`),save:mV(`save`),preset:hV,themeDefault:gV,doctor:vV,slash:yV,run:SV(e),do:CV});function dV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Sb(t,n,r,e);return i===null?null:{[e]:i}}}function fV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=wV(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 pV={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 mV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(X(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${pV[e]}), got ${kb(r[e])}`),null)}}function hV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return X(e,`${t}.preset`,`preset must be "save" or "delete", got ${kb(r)}`),null;if(r===`save`)return{preset:`save`};let a=Sb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function gV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(X(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${kb(n.themeDefault)}`),null)}const _V={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function vV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(_V,r),a=i?_V[r]:[...new Set(Object.values(_V).flat())];for(let r of Object.keys(n))a.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return X(e,`${t}.doctor`,`doctor must be ${Object.keys(_V).map(e=>`"${e}"`).join(`, `)}, got ${kb(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?JF:qF;if(typeof o!=`string`||!s.some(e=>e.name===o))return X(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${kb(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return hF.includes(c)?{doctor:`mark`,check:o,mark:c}:(X(e,`${t}.mark`,`doctor mark must be ${hF.map(e=>`"${e}"`).join(` or `)}, got ${kb(c)}`),null)}function yV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=SI(n.slash);return r.kind===`refused`?(X(e,`${t}.slash`,r.reason),null):{slash:r.line}}const bV=[`run`,`env`,`refreshes`],xV=/^[A-Za-z_][A-Za-z0-9_]*$/;function SV(e){return(t,n,r)=>{for(let e of Object.keys(r))bV.includes(e)||X(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${bV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&X(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${kb(a)}`);let o=r.env??{};(!Db(o)||Object.entries(o).some(([e,t])=>!xV.test(e)||typeof t!=`string`))&&X(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${kb(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&X(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${kb(s)}`),`dir`in e||X(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}}}xV.source;function CV(e,t,n){for(let r of Object.keys(n))r!==`do`&&X(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===``)?(X(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 ${kb(r)}`),null):{do:r}}function wV(e,t,n,r,i,a){let o=Sb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(X(e,s,i),null):o.includes(`/`)?(X(e,s,a(o)),null):o}const TV={set:`the SessionState key to write`,persist:`the config globals field to write`};function EV(e,t,n,r){let i=TV[r],a=wV(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 DV(e){return e===`set`?`set-state`:`set-config`}const OV={to:qV(`set`)},kV={to:qV(`persist`)},AV={from:JV(`set`)},jV={from:JV(`persist`)},MV={min:$V(),max:$V(),by:$V()},NV={int:XV()},PV={cycle:YV(`set`)},FV={cycle:YV(`persist`)},IV={removeSegment:ZV(`removeSegment`)},LV={insertSegment:ZV(`insertSegment`),anchor:ZV(`anchor`),relation:QV()},RV={insertSegmentFrom:JV(`persist`),anchor:ZV(`anchor`),relation:QV()},zV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},BV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function VV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Mb(e,t,n,r),c=Xb(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?Bb(s,...n):s}}const HV=[VV(`set`,OV),VV(`set`,AV),VV(`set`,MV,[zV,BV]),VV(`set`,NV),VV(`set`,PV)],UV=[VV(`persist`,kV),VV(`persist`,jV),VV(`persist`,MV,[zV,BV]),VV(`persist`,FV),VV(`persist`,IV),VV(`persist`,LV,[],[`insertSegment`]),VV(`persist`,RV,[],[`insertSegmentFrom`])];function WV(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 GV(e){let t=WV(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 KV(e,t,n,r,i){let a=EV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return X(e,t,`${GV(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)||X(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 qV(e){let t=DV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>wV(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 JV(e){let t=DV(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===``){X(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){X(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===``)){X(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){X(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){X(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}X(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${kb(o)}`)}}}function YV(e){let t=DV(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`)){X(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Ob(o)}`);return}let c=o;if(c.length<2){X(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){X(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){X(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){X(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function XV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){X(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${kb(r[n])}`);return}return!0}}}function ZV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Sb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){X(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){X(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 QV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){X(e,`${t}.${n}`,`relation must be "before" or "after", got ${kb(i)}`);return}return i}}}function $V(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){X(e,`${t}.${n}`,`${n} must be an integer, got ${kb(i)}`);return}return i}}}function eH(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const tH=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),nH=`plugin.json5`,rH=/^[a-z][a-z0-9_]*$/;function iH(e,t){let n=T.basename(T.dirname(e));return rH.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function aH(e){return`${e}.data`}function oH(e){return`${e}.json`}function sH(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:cH(e)}}}function cH(e){return e instanceof db?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 lH(e,t,n,r){return e.map(e=>iH(gP(T.dirname(t),e,r),n))}function uH(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:PS(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(T.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${nH}, and the folder's name is the plugin's: move this file to <dir>/<name>/${nH} and list that`;return c(t,o===void 0?e.config:fH(dH(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${T.basename(T.dirname(a))}" is not a plugin name (one matching ${rH}: 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=dH(e.config,o),d=sH(()=>{let i=s.readFileSync(a,`utf-8`),c=Iz(vH(a,n,{source:i,json:Ia.default.parse(i)},t),u);return NH(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,fH(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function dH(e,t){let n=FS(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 fH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:eH(n),definition:n.path}}}}function pH(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})=>FS(t)(e))}function mH(e,t){let n=pH(e.config),r=[...e.rendering.keys()].map(FS),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=LS(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:eH(e)})):[{definition:a.definition,notice:a.notice}]}}function hH(e,t,n){let r=pS(e.presets).flatMap(t=>[...zy(gS(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,gH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=pH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...SH.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=>iC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...pC(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 gH(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,_H(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function _H(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 vH(e,t,{source:n,json:r},{checkout:i,home:a}){let o=PS(t),c=[],l=()=>{throw new db(e,c)};if(!Db(r))return c.push({path:``,message:`a plugin definition must be an object, got ${Ob(r)}`}),l();for(let t of Object.keys(r))tH.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${T.basename(T.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...tH].join(`, `)}`});let u=r.data===void 0?void 0:IH(r.data,e,i,a,c),d=r.sources===void 0?{}:MH(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(Zv()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:sB(f,`data`,{[aH(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=sB(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 (.${aH(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,...TH(o,d),...TH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,DH(o,t)])))},segments:TH(o,OH(o,YB(f,r.segments,new Set))),helpers:TH(o,oV(f,r.helpers)),actions:TH(o,kH(o,sV(f,r.actions,{dir:s.realpathSync(T.dirname(e))})))};c.push(...CH(h,t));let g=yH(o,h);for(let[e,t]of wH(g))try{LN.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),g}function yH(e,t){let n=t=>hC(t,IS,e),r=t=>FS(`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=>bH(qy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(SH.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=>bH(qy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>xH(jS(e,n),r))}}function bH(e,t){return Ky(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function xH(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 SH=[`template`,`bg`,`fg`,`when`];function CH(e,t){let n=e.helpers??{},r=NS.filter(e=>e!==t.scope).map(e=>({scope:e,ns:PS({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>FS(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 ${PS(t)}: a plugin names itself without its scope — write ${s}${IS}${n.slice(o.ns.length)}`})},o=[...[...wH(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 eC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of iC(t,n))i===null&&a(e,r,!1);for(let n of pC(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))xH(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(Ky(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*wH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of Jy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of SH){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 Jy(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 AS(n))yield[`actions.${t}.${e}`,r]}function TH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function EH(e,t){return`${e}.${t}`}function DH(e,t){return t.kind===`state`?{...t,key:EH(e,t.key)}:t}function OH(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,DH(e,n)]))}]))}function kH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:EH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>EH(e,t))}:n]))}const AH=rH,jH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function MH(e,t,n){if(!Db(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${Ob(e)}`}),{};let r=T.join(s.realpathSync(T.dirname(t)),`session`),i=JSON.stringify(jH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!AH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${AH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=FH(o,jH,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 NH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=PH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=FS(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 db(e,a)}function PH(e){return T.join(e.storage,oH(`<session id>`))}function FH(e,t,n){return!Db(t)||!Db(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)?FH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function IH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return gP(T.dirname(t),e,r);if(Db(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(T.isAbsolute(t)||t.startsWith(`~`)||T.normalize(t).split(T.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 T.resolve(n.root,t)}if(Db(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 LH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>T.join(e,`cc-candybar`,`plugins`)),RH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:T.join(t,zH),scope:`repo`}]]}function RH(e){return T.join(e.dataHome,`cc-candybar`,`plugins`)}const zH=T.join(`.cc-candybar`,`plugins`);function BH(e,t){let n=LH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=VH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=iH(T.join(e,i,nH),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:T.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${nH}: move this file to ${T.join(e,`<name>`,nH)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function VH(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()||HH(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 HH(e,t){if(!t.isSymbolicLink())return!1;try{return s.statSync(T.join(e,t.name)).isDirectory()}catch{return!0}}const UH=[`approved`,`declined`];function WH(e){return e.link.kind===`linked`?e.link.main:e.dir}const GH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function KH(e,t){let n=WH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=GH(e.value,n),i=GH(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 qH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...KH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&KH(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 JH(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 YH(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(!UH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${UH.join(` or `)}`};return{kind:`ok`,value:e}}function XH(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 ZH(e){let t=XH(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 QH=[`json5`,`json`];function $H(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?QH.map(e=>T.join(t,`${eU}.${e}`)):[],...QH.map(e=>T.join(i,`${eU}.${e}`)),...QH.map(t=>`${tU(e)}.${t}`)])]}const eU=`.cc-candybar`;function tU(e){return T.join(e.configHome,`cc-candybar`,`config`)}function nU(e){return{path:e,scope:`plugins`}}function rU(e,t,n,r,i){let a=[],o=new Map;for(let t of $H(e,n,r,i)){let n=Fz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=s.realpathSync.native(T.dirname(t)),c=T.join(r,T.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||iU(e,t)?null:{dir:r,link:Vc(r)}})}let c=[...o.values()],l=qH(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),aU(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:oU(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 iU(e,t){return QH.some(n=>t===`${tU(e)}.${n}`)}function aU(e){if(e===void 0||Fz(e)!==`present`)return null;let t=VH(T.join(e,zH)),n=s.realpathSync.native(e);return{dir:n,link:Vc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function oU(e,t){return t.find(t=>iU(e,t.path))?.path??`${tU(e)}.${QH[0]}`}function sU(e,t,n,r,i){let a=rU(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 cU(e){return lU(e).join(`
|
|
180
|
+
`)||null}function lU(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 uU(e,t,n){let r=$H(e,t,n).filter(e=>Fz(e)===`present`),i=new Map;for(let e of r){let t=T.dirname(e),n=T.basename(e).replace(/\.(json5|json)$/,``),r=T.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 dU(e,t,n,r){let i=T.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&&On(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const fU={level:`error`,glyph:`⚠`,colors:jP},pU={level:`warning`,glyph:`⚠`,colors:MP},mU={level:`warning`,glyph:`⬆`,colors:MP},hU={level:`warning`,glyph:`🔒`,colors:MP},gU={level:`warning`,glyph:`🧪`,colors:MP};function _U(e,t){return{text:PP(e),link:t}}function vU(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=yU(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,fU)),...r,...i.flatMap(e=>o(e,pU))],c=bU(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[_U(n.lines[0][0].text,xU(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function yU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>_U(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 bU(e){return TU(e).map(e=>String(e*CU+1))}function xU(e,t,n,r){return Ta([{verb:ma,args:[e,t,n]}],`copy diagnostic ${r}`)}function SU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const CU=4096;function wU(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 TU(e){let t=new Map;return e.map(e=>{let n=wU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function EU(e,t,n){return String(TU(e)[t]*CU+n+1)}const DU={error:jP,warning:MP};function OU(e){let t=SU(e),n=e.length,r=DU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:EU(e,0,0)}}function kU(e,t){let n=Number(e)-1,r=TU(t).indexOf(Math.floor(n/CU));return e===null||r===-1?null:{index:r+1,page:n%CU}}function AU(e,t){return Math.min(20,e??20,...t)}function jU(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=PU(i),c=LU(o,s,[]),l=new W({bgcolor:o.severity.colors.bg,color:o.severity.colors.fg}),u=(e,t)=>FU(e,t===null?l:l.withLink(t)),d=(t,r)=>r===null?u(` `,null):u(t,NU(n,EU(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),f=(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,f=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return IU([u(`✕`,NU(n,`0`)),...l?[d(`‹`,o)]:[],u(f,null),...l?[d(`›`,c)]:[],u(`⧉ copy`,xU(n,r,EU(e,a-1,0),a))],s)},p=1;for(;;){let e=Math.max(1,i.rows-p),n=Math.min(CU,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=f(n,r);if(a.length>p){p=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,d=r===n-1&&l>0?[...o.slice(0,-1),...IU([u(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...d]}}function MU(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=OU(t),c=i===``?[]:[FU(i,new W({bgcolor:o,color:a}).withLink(NU(n,s)))];return LU(e,PU(r),c)}function NU(e,t,n){return Ta([{verb:Wi,args:[e,Bi,t]}],n)}function PU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const FU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),IU=(e,t)=>eF(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function LU(e,t,n){let r=new W({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=bl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=FU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Cl(e,a)).map(t=>FU(t,i(e.link)))),u=s===0?n:[];return IU([c,...l,...u],t)})}const RU=`repo-configs.json`;function zU(e){return T.join(e,`repo-configs`)}function BU(e){return T.join(zU(e),RU)}const VU=e=>{let t=dU(zU(e),RU,{},YH),n=dU(e,RU,{},YH),r=()=>s.existsSync(BU(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 HU(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:Fz(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&WH({dir:e,link:Vc(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]:[])},JH(e,t,n,r.superseded)});return i.kind===`failed`?i:I(r)}function UU(e,t,n){return{sessionId:e,action:pa,declaration:t,evaluated:n}}function WU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=UH.map(r=>_U(`[${r===`approved`?`approve`:`decline`}]`,Ta([{verb:pa,args:[t,e,r,n.sign(UU(t,e,r))]}]))),a=[_U(r,null),...i];return{severity:hU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function GU({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const KU=`render-origin`,qU=`client-hints`;function JU(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const YU={kind:`hidden`},XU={kind:`shown`};function ZU(e,t){try{return JU(e,t)?XU:YU}catch(e){let t=jC(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function QU(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function $U(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function eW({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function tW({text:e,placement:t,lead:n,trail:r}){return{text:nW(e),placement:t,...n!==void 0&&{lead:nW(n)},...r!==void 0&&{trail:nW(r)}}}function nW(e){let t=e.blankCopy(e.plain);t.style=wP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(wP(i).clearMetaAndLinks(),n,r);return t}function rW(e){let t=eW(e);if(t.length===1)return e.text;let n=QU(t);return n.style=e.text.style,n}function iW(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=QU(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:QU([d,...c],a)},...l.length>0&&{trail:QU([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:($U(u,n,p),[{text:u,...f}])}function aW(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return Mte(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 oW(e,t){if(e.length===0)return 0;let{lines:n}=eF(e.map(({owner:e})=>e),t),r=B(WP(n[n.length-1]));return Math.max(0,r-XP(t)+ZP(t))}function sW(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=eF([e],{...n,width:1/0});return B(WP(r.flat()))<=n.width}function cW(e,t,n,r){if(sW(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=oW(n,r);return i.divide(aW(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 lW(e,t){let n=Math.max(2,$P(t)-XP(t)-t.padding);return uW(e,t).reduce((e,r)=>[...e,...cW(r,n,e,t)],[])}function uW(e,t){let n=()=>e.map(e=>({owner:rW(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=eF(e.map(rW),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(WP(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];$U(c,c.cellLength+a,n)}),n()}function dW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=fW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:wP(a.style)};if(e.style.link){i();let r=fW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function fW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>pW(e.frag,n?n.add(e.style):e.style)),i=q.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function pW(e,t){let n=e.copy();return n.style=t,n}function mW(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 hW(e,t){let{look:n}=mW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function gW(e,t){let{layout:n}=mW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function _W(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 vW(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,yW(e,t,o,n,r,i));return i}function yW(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=zx.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:SW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:SW(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:kS(n),argv:n.run.map(n=>SW(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,SW(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:SW(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 bW(e){return e.kind===`do`?bW(e.head):e}function xW(e){switch(bW(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 SW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function CW(e,t){return e.has(t)?DC(e.read(t)):``}function wW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function TW(e,t,n,r){let i=new q(e,{style:W.combine([r,new W({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function EW(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([wP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([wP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function DW(e,t){return Math.max(e.members.indexOf(CW(t,e.stateVar)),0)}function OW(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=CW(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=CW(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=CW(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(DW(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:[wW(e.text,ej(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[wW(e.target,ej(r))]}],active:!1};case`persist-literal`:{let t=CW(r,e.stateVar);return{effects:[{verb:Yi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=CW(r,e.stateVar);return{effects:[{verb:Yi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(DW(e,r)+1)%e.members.length];return{effects:[{verb:Yi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Xi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ta,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ra,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`back`:return{effects:[{verb:aa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:oa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Zi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ea,args:[i,wW(e.name,ej(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ca,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:la,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:ua,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:fa,args:[i,e.line]}],active:!1};case`run`:{let t=ej(r),n=JSON.stringify({run:e.argv.map(e=>wW(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,wW(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:na,args:[i,e.key,$R(e.op)]}],active:!1};case`do`:{let o=OW(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>OW(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:na,args:[i,e.key,$R(r)]}],active:!1}}}}function kW(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,DW(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 AW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=mW(n,`action "${e}"`).store,{display:a,boundValue:o}=kW(e,bW(r),t,i),s=CW(i,`session.id`),{effects:c,active:l}=OW(r,a.plain,o,i,s,n.signer);return EW(a,Ta(c),l)}function jW(e){return{action:{fn:(t,...n)=>AW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function MW(e,t){return TW(`✕`,Ta([{verb:Wi,args:[CW(e,`session.id`),t,P]}]),!1)}function NW(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(wv(e,t,n))})}function PW({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function FW(e,t,n){return new W({color:U.fromRgba(ld(e.get(`warning`),t,Cv,n))})}function IW(e,t,n){return W.combine([NW(e,t,n),FW(e,t,n)])}function LW(e,t,n){return PW(Iv(e.palette,e.disclosure,t,n))}function RW(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(E_.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const zW=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},BW=e=>new W({bold:e});function VW(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>zW(a,W.combine([LW(e,{...n,distribution:t},i),BW(o)]));let o=NW(e.palette,a,i);return(e,t,i,a)=>HW(i,W.combine([o,BW(a)]),r(t,n))}const HW=(e,t,n)=>zW(q.fromFragments([zW(e,t),zW(` `,t),RW(n)]));function UW(e,t,n,r){return t===void 0?zW(r):HW(r,void 0,t(n,e))}function WW(e,t,n,r,i){let a=NW(e.palette,i,r);return(e,r,i,o)=>zW(q.fromFragments([zW(o?`[`:` `,a),RW(n(r,t)),zW(o?`]`:` `,a)]))}function GW(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=>KW(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function KW(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function qW(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function JW(e){return{current:null,drawnAt:e}}function YW(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 XW(e,t,n){return QW(e,()=>n(YW(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function ZW(e,t){return QW(e,()=>(e.current=null,t()))}function QW(e,t){let n=e.current;try{return t()}finally{e.current=n}}function $W(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 eG(e){return new q(e).cellLength}function tG(e){let{width:t,chromeCols:n,padding:r}=mW(e,`a row fit`);return Math.max(1,t-n-2*r)}function nG(e){let{padding:t,seamCols:n}=mW(e,`a row fit`);return Math.max(1,tG(e)-(eG(`✕`)+2*t+n))}function rG(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 iG(e,t,n){let r=eG(`←`)+1+eG(`→`)+1,i=rG(e,t,n);return(i.length>1?rG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function aG(e){let t=[];for(let n of e)t.length>0&&t.push(new q(` `)),t.push(n);let n=q.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function oG(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 sG(e,t,n){let r=e.compiled.get(t),i=r&&bW(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 cG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=mW(a,`picker`).store,d=CW(u,`session.id`),f=`stateVar`in t?CW(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`?nG(a):tG(a):1/0,h=(r.kind===`led`?0:eG(`✕`)+1)+c.reduce((e,t)=>e+eG(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?iG(v.map(e=>e.cellLength),m,h):GW(g.entries,g.groups,i),b=parseInt(CW(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,ee=y[C]??[],w=e=>Ta([{verb:Wi,args:[d,n.key,String(e)]}]),te=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?te:[],T=e=>Ta([...OW(l,e,e,u,d,a.signer).effects,...ne]),re=(e,n)=>EW(e,T(t.options[n])),E=r.kind===`led`?[]:[TW(`✕`,Ta(te),!1,s)];E.push(...c.map(({glyph:e,option:r})=>TW(e,Ta([...OW(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&E.push(TW(`←`,w(C-1),!1));let D=C<y.length-1?[TW(`→`,w(C+1),!1)]:[];if(g===void 0){let e=ee.flatMap(e=>e.indices);return[aG([...E,...e.map(e=>re(v[e],e)),...D])]}let ie=new W({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=ee.length===1?[new q(`${ee[0].label}${O}`,{style:ie})]:[],oe=[aG([...E,...ae,...D])];for(let e of ee){ee.length>1&&oe.push(aG([new q(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>eG(_(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:PP(i),o=` `.repeat(n-eG(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(aG([re(p(r,qW(s,m)),r)]))}}return oe}function lG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{MA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=oG(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=sG(e,n,`picker`),u=$W(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=>cG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,VW(u,cv(void 0),hW(e,`{{ picker }}`),l.paletteOf,d,t),FW(u.palette,t,d)),p=Pv(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 uG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function dG(e,t,n,r,i){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=mW(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=CW(a,`session.id`),{options:c}=t;if(c.length===0)return aG([]);let l=uG(c,CW(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ta(OW(o,u(e),u(e),a,s,i.signer).effects);return aG([TW(`◀`,d(-1),!1),EW(UW(hW(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ta(OW(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),TW(`▶`,d(1),!1)])}function fG(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(xW(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 dG(t,sG(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function pG(e,t,n){let r=sG(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 mG(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 hG(e,t,n,r){let i=pG(e,t,n),a=r??CW(mW(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,hW(e,`{{ ${n} }}`))}function gG(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(MA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return RW(hG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function _G(e,t,n){return{swatches:{fn:(r,i)=>{let a=pG(e,r,`swatches`),o=oG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=$W(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]=cG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,WW(s,hW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),FW(s.palette,s.bg,c),u===0?[]:(()=>{let t=uG(l,CW(mW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[mG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const vG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function yG(e,t,n,r){let i=Pv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:wv(e,n,r)});return[[J_(e,t,r).map((n,i)=>{let a=Sv(e,n);return{text:vG[i%vG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function bG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new q(` ${e} `,{style:PW({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 q(e)),r.push(a)}return r}function xG(e,t,n,r,i){let a=yG(e,t,n,r).map(e=>bG(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
|
|
181
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function SG(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(MA(`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}=hW(e,`{{ themePreview }}`);return xG(r===void 0?a:hG(e,r,`themePreview`),o,{...$W(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),nG(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const CG=e=>e.slice(e.lastIndexOf(`.`)+1),wG=(e,t)=>{let n=new q(CG(e));return n.truncate(t,{marker:`…`}),n.plain};function TG(e,t){let n=e.map(e=>e.map(({name:e})=>eG(CG(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 EG(e,t,n,r){let i=TG(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new q(` ${wG(s,i)} `,{style:PW(Kv(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
|
|
182
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const DG=`layoutPreview`;function OG(e,t){return{[DG]:{fn:()=>EG(gW(e,`{{ layoutPreview }}`),hW(e,`{{ layoutPreview }}`).decor,t.drawnAt(),nG(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function kG(e,t,n,r){let i=$W(r.activeSegment,`{{ menu }}`),a=r.action,o=EM(i.placementId,e,n.key),s=kM(o),c=TM(e),l=mW(a,`menu`).store,u=CW(l,o)===c,d=CW(l,`session.id`),f=u?P:c,p=TW(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=Pv(i.palette,i.disclosure,t).plane,l=sG(a,e,`menu`);return cG(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,P],[s,`0`]],onPick:n.closeOnPick},n.paged,a,VW(i,n.distribution,hW(a,`{{ menu }}`),l.paletteOf,t,c),FW(i.palette,c,t))})():[]),p}const AG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jG(e,t){let n=t[t.length-1],r=AG(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:NM(r??{})}}function MG(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=jG(t,n);return kG(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function NG(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=PG(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 q(t?i:a,{style:l===void 0?void 0:new W({color:l})}))}let l=q.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function PG(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 FG(e){let t={fn:(()=>{let t=$W(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:(()=>$W(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=$W(e,`{{ roleTextOn }}`);return RG(r,t,Zu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=$W(e,`{{ keptOn }}`),i=Zu(r,t),a=Zu(r,n),o=Ll(dd(i,H.TRUECOLOR),dd(a,H.TRUECOLOR)),s=Math.min(Cv,Math.max(o,3));return(ud(i,e.drawnAt(),(e,t)=>Ll(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=pA(()=>$W(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...zG(s)];return NG({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 IG={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},LG=Object.values(IG).flat();function RG(e,t,n){let r=dd(n,H.TRUECOLOR),i=t=>{let n=Zu(e,t);return{colour:n,ratio:Ll(dd(n,H.TRUECOLOR),r)}},a=cd(r).hex,o=IG[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,...LG.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 zG(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function BG({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),[...[...AS(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=YS(e=>{let i=lC(e,t)?Object.keys(n):iC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=YS(n=>i(n).flatMap(n=>[...eC(n,t).keys()].map(t=>({path:t,reaches:vC(t,e)}))));return{ofTemplate:a,calls:YS(e=>new Set(i(e).flatMap(e=>[...dC(e,t)]))),ofVariable:t=>[...Jy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...Ky(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function VG(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const HG=new WeakMap;function UG(e){let t=HG.get(e);return t===void 0&&(t=BG({names:new Set([..._C(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),HG.set(e,t)),t}function WG(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>QA.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const GG={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,dropped:`directory`,source:`view`},KG=new WeakMap;function qG(e){let t=KG.get(e);return t===void 0&&(t=JG(e),KG.set(e,t)),t}function JG(e){let t=new Map(_C(e)),n=UG(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:GG[t.kind]])),i=new Map([...t].map(([e,t])=>[e,WG(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function YG(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
183
183
|
`)){n.push(r);continue}let e=r.split(`
|
|
184
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function YG(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 XG=e=>e.kind===`failed`?JU:e;function ZG(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function QG(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 $G(e){return{...e,cells:e.cells.map(eW)}}function eK(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,...tK(e,r)]}function tK(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 nK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:eK(e.direction,e.children.map((t,i)=>n(t,[...r,rK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function rK(e,t){return e.steps[t]}function iK(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=aK(e);return{width:oK(t),reach:sK(t)}}function aK(e){let t=e.children.map(iK),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 oK=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),sK=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function cK(e,t){let n=aK(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=Py[e.direction],i=cv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),sK(n),oK(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const lK={compile(e,t){let n=cK(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,By(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),eK(e.direction,e.children.map((n,r)=>t.renderChild(n,XG(t.gate),rK(e,r))))}},uK={drop:e=>e.place,above:()=>`above`},dK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},fK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:Fy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Vy(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,pK(e,t))};function pK(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=tj(t.scope,e.settings);if(t.gate.kind===`failed`)return yK(e,r,t,t.gate.message);try{let i=t.placement(e),a=ZG(t.gate,i.gate());if(a.kind===`failed`)return yK(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 yK(e,r,t,s.message);let c=Wx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:tP(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`?mK(f.variable):hK(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?gK(p.segment,u):_K(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:JU,h.disclosure).map(e=>({...e,place:uK[v.placement](e)})),b=(e,t,n)=>rW(uW([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?dK[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new q(` `.repeat(vK($U(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap($U)),[...ne,...te]}catch(n){return yK(e,r,t,n.message??String(n))}}const mK=e=>({kind:`waiting`,variable:e});function hK(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=AC(e);if(t===void 0)throw e;return mK(t.variable)}}function gK(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:JG(uW(r,c)).map((e,t)=>({cells:rW(e,{...l,lead:t===0?uW(i,c):[],trail:t===0?uW(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:rW(uW([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function _K(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=uW(bK(e.lead,e,t,n),l),d=uW(bK(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 rW(uW([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function vK(e){return e.reduce((e,t)=>e+t.cellLength,0)}function yK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:rW([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:tP(n.palette)},lead:bK(e.lead,e,t,n),trail:bK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function bK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=AC(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const xK={container:lK,segment:fK};function SK(e){return xK[e]}var CK=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?wK:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const wK={kind:`hidden`},TK={palette:`theme`,style:`style`,effect:`effect`},EK=Rx.get(`colorCompatibility`),DK={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function OK(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function kK(e){if(e.ok)return e.value;throw e.error}const AK=e=>({read:()=>e}),jK=w_({basePalette:C_,palette:C_,decor:zv});var MK=class{evaluated=0;memory=new CK;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&jK(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=Y.observable.box(r,{deep:!1}),this.scope=$A(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(EK);return e.kind===`found`&&typeof e.value==`string`&&Cy(e.value)?e.value:`truecolor`});let i=(0,Y.observable)(DK,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 nK(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=VR(e);return i===void 0?[]:[{name:i,address:n,palette:Wx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>wy(this.colorCompatibility())})}bind(e){(0,Y.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,Y.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=bM(e);return t===void 0?vM(e)===void 0?sM(this.view.get().payload(),e):sM(this.projected,e):oM(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()[TK[e]];if(t.kind===`decided`)return FK(t.name,null,null);let r=LK(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=RK(this.source,e,i.name,r.where,e=>{t=e}),FK(n,t,null)}case`pending`:return FK(n??uy[e],null,i.variable);case`failed`:return n=uy[e],FK(n,dy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!IK(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)??uy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,Y.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return XU(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>XW(this.source.activeSegment,()=>XU(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new zK(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:gW(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=AC(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:OK(e)}),kK(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:VR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function NK(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new MK(t,n,e,r);return e.views.set(t,a),a}function PK(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 FK=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),IK=(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 LK(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 RK(e,t,n,r,i){switch(t){case`palette`:return Jx(n,r,i).name;case`style`:return sy(n,e.styles).name;case`effect`:return _y(n).name}}var zK=class{where=BK(w_({palette:C_,region:Lv}));ground=BK(w_({colours:HK,bodyOpen:C_}));opened=BK(w_({colours:HK,open:C_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=tj(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?AK(YU):e.derive(`${t.id} when`,e.readsInstant(a),()=>XW(r,()=>XU(a,i))),this.open=d===void 0?AK(JU):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>XW(r,()=>XU(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return GK(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 KK(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?AK(JK):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return qK(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}),XK(n,r,this.affixes.read())}};function BK(e){let t=Y.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,Y.runInAction)(()=>t.set(e)),get:()=>t.get()}}const VK=(e,t)=>e.hex===t.hex,HK=w_({palette:C_,drawnAt:C_,tint:VK,text:VK,bg:VK,disclosure:Bv});function UK(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const WK=e=>Pv(e.palette,e.disclosure,e.drawnAt);function GK(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Kv(n,r,i)};return YW(e,UK(t,c),e=>{let t=rP(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function KK(e,t,n,r,i,a){return YW(e,UK(t,n),e=>(e.bg=i?WK(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function qK(e,t,n,r,i,a,o){return YW(e,UK(t,n),e=>(e.bg=r?WK(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const JK={lead:[],trail:[],drops:[]};function YK(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return MW(t,WK(e).state,n)},get band(){return MW(t,WK(e).plane,n)},get close(){return FW(t,WK(e).state,n)},disclosure:r}}function XK(e,t,n){return{styles:YK(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function ZK(e,t,n,r,i,a,o){let s=GK(e,t,n,r,i,void 0,void 0,o);return XK(s,KK(e,t,s,a,!1,o),JK)}function QK(e,t,n,r,i){return YK(GK(e,t,n,r,i,void 0,void 0,{}))}function $K(e,t){return{payload:()=>e,selections:()=>t}}function eq(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 tq=new WeakMap;function nq(e){let t=tq.get(e);return t===void 0&&(t=iq(e),tq.set(e,t)),t}function rq(e){return nq(e).projections}function iq(e){let t=new Map(gC(e)),n=new Map,r={reads:HG(e),projections:n,clock:JA};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=BG(e,r),i=t===void 0?null:vM(t);i&&n.set(e,`reads the draw's "${i}" (${_M[i]})`)}let i=oq(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=eq(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of ny)if(!a.has(t))for(let n of i[t]){let i=eq(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=BG(r,i);if(t===void 0||n.has(r))continue;let o=bM(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 aq(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>ny.flatMap(n=>{let r=t[n];return ry(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function oq(e){let t=aq(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function sq(e,t){return eq(e,nq(t))}function cq(e){return t=>eq(t,e)!==null}function lq(e){if(`ttl`in e)return{kind:`ttl`,durationMs:nM(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 uq(e,t){switch(Wy(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 dq(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:lq(n.cache),parse:uq(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:lq(n.cache),parse:uq(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 fq(e,t,n,r=vw.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 pq(e,t,n){let{compiled:r,loadWarnings:i}=hq(e,t,n.cwd,mq(n.signer),yq);return{...r,loadWarnings:i}}const mq=e=>(t,n)=>bq(n,e);function hq(e,t,n,r,i=yq){let a=gq(e),o=_q(a);return{compiled:r(o,a),compileKey:o,loadWarnings:vq(e,t,n,i)}}function gq(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of zx)n in t&&r.set(e,n);for(let[t,n]of Zy(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...rq(e)].sort(([e],[t])=>e<t?-1:1)}}function _q(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function vq(e,t,n,r){let i=KG(e),a=rq(e),o=[];for(let[s,c]of gC(e))if(r.has(i.get(s)))try{dq(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const yq=new Set([`directory`,`view`]);function bq({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>pW(i,`drawnAt`).registry.drawnAt(),o=qW(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=fS(e.presets),u=AR(e),d=[e=>gG(i,o,e.now)],f=QA({extraFuncs:{...AW(i),...hG(i),...cG(i,o),...dG(i),...xG(i,o),...DG(i,o),...jG(s),...PG(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=fq(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=_W(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:fq(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=tb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>sb(t,e,a,t=>String(pW(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 SK(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=hS(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(ny.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of aq(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:Cq(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w=new Set(n.map(([e])=>e)),te={reads:zG({names:w,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:YA(d)},ne=cq(te),T=[...C.values()].flatMap(Sq(y)).some(e=>ne(m.get(e))),re=T?new Set([...te.clock,EG]):te.clock,E=cq({...te,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=cq({reads:zG({names:w,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:te.projections,clock:re});for(let e of xH){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function xq(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 Sq=e=>t=>{let n=[];return nK(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 Cq(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 wq=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function Tq(e,t,n,r,i){let a=Eq(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function Eq(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??uy[e];case`failed`:return r({kind:`rule`,slot:e,message:dy(t.where,e,`the rule failed — ${n.error}`)}),uy[e]}}function Dq(e){return Oq(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function Oq(e){return e.kind===`container`?e.children.flatMap(Oq):[e,...e.opens===void 0?[]:Oq(e.opens.body)]}function kq(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return NK(e,t,n,$K(o,a)),o}function Aq(e,t,n,r,i,a,o,s,c){try{var l=No();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new kP(``),h=m.clockAt(a,py[c.animationSpeed]),g=l.u(zA(a,h.timeline)),_=PK(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:YP(v),padding:v.padding,seamCols:XP(v),preset:c.preset},i);let y=_.evaluated;l.u(gW(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:K_[c.variation],shade:L_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,QG),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.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&&te.add(n.waited),n.name;let r=RK(t,e,Tq(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:Jx(re(`palette`),``,wq),ae=D.kind===`decided`?D:sy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:_y(re(`effect`)),se=O.value,ce=Kx(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:wv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:QG,hold:$G},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:ZG(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${Dq(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>ZK(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Wv(a,n)),renderBody:(e,t,n)=>pe(e,t,Gv(n)),closeDisclosure:e=>jW(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>QK(t.activeSegment,e,n,a,r.drawnAt())};return SK(e.kind).render(e,c)},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 "${uS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=YG(pe(me,YU,Uv(S))).map(({line:e,row:t})=>{let n=cW(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...$P(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||Oq(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:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}function jq(e){return Math.max(1,e-2)}function Mq(e,t){return e.kind===`absent`?I(`none`):e.kind===`failed`?e:t.kind===`failed`?t:I(t.kind===`ok`?`tracked`:`gone`)}function Nq(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?R(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const Pq={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},Fq={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Iq(e,t,n){return Object.hasOwn(t,n)?I(t[n]):R(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const Lq={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function Rq(e){return Object.keys(Lq).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${Lq[t]}: ${n.reason}`]:[]})}function zq(e,t,n){return t.ok?I(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?L:R(Bq(e,t),`read`)}function Bq(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Vq(t.stderr)].filter(Boolean).join(`, `)}`}function Vq(e){return e.trim().split(`
|
|
185
|
-
`,1)[0]??``}function
|
|
186
|
-
`)){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
|
|
187
|
-
`)){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)`?L:I(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=I(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=I({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
|
|
188
|
-
`).length:0)}async getRemotesAsync(e){let t=
|
|
184
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function XG(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 ZG=e=>e.kind===`failed`?YU:e;function QG(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function $G(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 eK(e){return{...e,cells:e.cells.map(tW)}}function tK(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,...nK(e,r)]}function nK(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 rK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:tK(e.direction,e.children.map((t,i)=>n(t,[...r,iK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function iK(e,t){return e.steps[t]}function aK(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=oK(e);return{width:sK(t),reach:cK(t)}}function oK(e){let t=e.children.map(aK),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 sK=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),cK=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function lK(e,t){let n=oK(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=Py[e.direction],i=cv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),cK(n),sK(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const uK={compile(e,t){let n=lK(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,By(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),tK(e.direction,e.children.map((n,r)=>t.renderChild(n,ZG(t.gate),iK(e,r))))}},dK={drop:e=>e.place,above:()=>`above`},fK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},pK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:Fy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ci(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Vy(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,mK(e,t))};function mK(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=nj(t.scope,e.settings);if(t.gate.kind===`failed`)return bK(e,r,t,t.gate.message);try{let i=t.placement(e),a=QG(t.gate,i.gate());if(a.kind===`failed`)return bK(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 bK(e,r,t,s.message);let c=Gx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:nP(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`?hK(f.variable):gK(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?_K(p.segment,u):vK(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:YU,h.disclosure).map(e=>({...e,place:dK[v.placement](e)})),b=(e,t,n)=>iW(dW([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?fK[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new q(` `.repeat(yK(eW(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap(eW)),[...ne,...te]}catch(n){return bK(e,r,t,n.message??String(n))}}const hK=e=>({kind:`waiting`,variable:e});function gK(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=jC(e);if(t===void 0)throw e;return hK(t.variable)}}function _K(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:YG(dW(r,c)).map((e,t)=>({cells:iW(e,{...l,lead:t===0?dW(i,c):[],trail:t===0?dW(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:iW(dW([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function vK(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=dW(xK(e.lead,e,t,n),l),d=dW(xK(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 iW(dW([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function yK(e){return e.reduce((e,t)=>e+t.cellLength,0)}function bK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:iW([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:nP(n.palette)},lead:xK(e.lead,e,t,n),trail:xK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function xK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=jC(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const SK={container:uK,segment:pK};function CK(e){return SK[e]}var wK=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?TK:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const TK={kind:`hidden`},EK={palette:`theme`,style:`style`,effect:`effect`},DK=zx.get(`colorCompatibility`),OK={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function kK(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function AK(e){if(e.ok)return e.value;throw e.error}const jK=e=>({read:()=>e}),MK=w_({basePalette:C_,palette:C_,decor:zv});var NK=class{evaluated=0;memory=new wK;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&MK(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=Y.observable.box(r,{deep:!1}),this.scope=ej(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(DK);return e.kind===`found`&&typeof e.value==`string`&&Cy(e.value)?e.value:`truecolor`});let i=(0,Y.observable)(OK,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 rK(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=VR(e);return i===void 0?[]:[{name:i,address:n,palette:Gx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>wy(this.colorCompatibility())})}bind(e){(0,Y.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,Y.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=xM(e);return t===void 0?yM(e)===void 0?cM(this.view.get().payload(),e):cM(this.projected,e):sM(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()[EK[e]];if(t.kind===`decided`)return IK(t.name,null,null);let r=RK(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=zK(this.source,e,i.name,r.where,e=>{t=e}),IK(n,t,null)}case`pending`:return IK(n??uy[e],null,i.variable);case`failed`:return n=uy[e],IK(n,dy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!LK(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)??uy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,Y.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return ZU(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>ZW(this.source.activeSegment,()=>ZU(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new BK(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:_W(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=jC(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:kK(e)}),AK(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:VR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function PK(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new NK(t,n,e,r);return e.views.set(t,a),a}function FK(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 IK=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),LK=(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 RK(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 zK(e,t,n,r,i){switch(t){case`palette`:return Yx(n,r,i).name;case`style`:return sy(n,e.styles).name;case`effect`:return _y(n).name}}var BK=class{where=VK(w_({palette:C_,region:Lv}));ground=VK(w_({colours:UK,bodyOpen:C_}));opened=VK(w_({colours:UK,open:C_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=nj(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?jK(XU):e.derive(`${t.id} when`,e.readsInstant(a),()=>ZW(r,()=>ZU(a,i))),this.open=d===void 0?jK(YU):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>ZW(r,()=>ZU(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return KK(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 qK(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?jK(YK):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return JK(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}),ZK(n,r,this.affixes.read())}};function VK(e){let t=Y.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,Y.runInAction)(()=>t.set(e)),get:()=>t.get()}}const HK=(e,t)=>e.hex===t.hex,UK=w_({palette:C_,drawnAt:C_,tint:HK,text:HK,bg:HK,disclosure:Bv});function WK(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const GK=e=>Pv(e.palette,e.disclosure,e.drawnAt);function KK(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Kv(n,r,i)};return XW(e,WK(t,c),e=>{let t=iP(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function qK(e,t,n,r,i,a){return XW(e,WK(t,n),e=>(e.bg=i?GK(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function JK(e,t,n,r,i,a,o){return XW(e,WK(t,n),e=>(e.bg=r?GK(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const YK={lead:[],trail:[],drops:[]};function XK(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return NW(t,GK(e).state,n)},get band(){return NW(t,GK(e).plane,n)},get close(){return IW(t,GK(e).state,n)},disclosure:r}}function ZK(e,t,n){return{styles:XK(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function QK(e,t,n,r,i,a,o){let s=KK(e,t,n,r,i,void 0,void 0,o);return ZK(s,qK(e,t,s,a,!1,o),YK)}function $K(e,t,n,r,i){return XK(KK(e,t,n,r,i,void 0,void 0,{}))}function eq(e,t){return{payload:()=>e,selections:()=>t}}function tq(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 nq=new WeakMap;function rq(e){let t=nq.get(e);return t===void 0&&(t=aq(e),nq.set(e,t)),t}function iq(e){return rq(e).projections}function aq(e){let t=new Map(_C(e)),n=new Map,r={reads:UG(e),projections:n,clock:YA};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=VG(e,r),i=t===void 0?null:yM(t);i&&n.set(e,`reads the draw's "${i}" (${vM[i]})`)}let i=sq(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=tq(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of ny)if(!a.has(t))for(let n of i[t]){let i=tq(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=VG(r,i);if(t===void 0||n.has(r))continue;let o=xM(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 oq(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>ny.flatMap(n=>{let r=t[n];return ry(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function sq(e){let t=oq(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function cq(e,t){return tq(e,rq(t))}function lq(e){return t=>tq(t,e)!==null}function uq(e){if(`ttl`in e)return{kind:`ttl`,durationMs:rM(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 dq(e,t){switch(Wy(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 fq(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`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:uq(n.cache),parse:dq(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:uq(n.cache),parse:dq(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 pq(e,t,n,r=yw.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 mq(e,t,n){let{compiled:r,loadWarnings:i}=gq(e,t,n.cwd,hq(n.signer),bq);return{...r,loadWarnings:i}}const hq=e=>(t,n)=>xq(n,e);function gq(e,t,n,r,i=bq){let a=_q(e),o=vq(a);return{compiled:r(o,a),compileKey:o,loadWarnings:yq(e,t,n,i)}}function _q(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Bx)n in t&&r.set(e,n);for(let[t,n]of Zy(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...iq(e)].sort(([e],[t])=>e<t?-1:1)}}function vq(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function yq(e,t,n,r){let i=qG(e),a=iq(e),o=[];for(let[s,c]of _C(e))if(r.has(i.get(s)))try{fq(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const bq=new Set([`directory`,`view`]);function xq({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>mW(i,`drawnAt`).registry.drawnAt(),o=JW(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=pS(e.presets),u=AR(e),d=[e=>_G(i,o,e.now)],f=$A({extraFuncs:{...jW(i),...gG(i),...lG(i,o),...fG(i),...SG(i,o),...OG(i,o),...MG(s),...FG(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=pq(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=vW(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:pq(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=tb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>sb(t,e,a,t=>String(mW(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 CK(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=gS(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(ny.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of oq(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:wq(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w=new Set(n.map(([e])=>e)),te={reads:BG({names:w,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:XA(d)},ne=lq(te),T=[...C.values()].flatMap(Cq(y)).some(e=>ne(m.get(e))),re=T?new Set([...te.clock,DG]):te.clock,E=lq({...te,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=lq({reads:BG({names:w,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:te.projections,clock:re});for(let e of SH){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function Sq(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 Cq=e=>t=>{let n=[];return rK(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 wq(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 Tq=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function Eq(e,t,n,r,i){let a=Dq(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function Dq(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??uy[e];case`failed`:return r({kind:`rule`,slot:e,message:dy(t.where,e,`the rule failed — ${n.error}`)}),uy[e]}}function Oq(e){return kq(e).filter(e=>!e.name.startsWith(Pi)).map(e=>e.id)}function kq(e){return e.kind===`container`?e.children.flatMap(kq):[e,...e.opens===void 0?[]:kq(e.opens.body)]}function Aq(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return PK(e,t,n,eq(o,a)),o}function jq(e,t,n,r,i,a,o,s,c){try{var l=No();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new AP(``),h=m.clockAt(a,py[c.animationSpeed]),g=l.u(BA(a,h.timeline)),_=FK(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:XP(v),padding:v.padding,seamCols:ZP(v),preset:c.preset},i);let y=_.evaluated;l.u(_W(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:K_[c.variation],shade:L_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,$G),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.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&&te.add(n.waited),n.name;let r=zK(t,e,Eq(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:Yx(re(`palette`),``,Tq),ae=D.kind===`decided`?D:sy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:_y(re(`effect`)),se=O.value,ce=qx(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:wv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:$G,hold:eK},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:QG(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${Oq(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>QK(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Wv(a,n)),renderBody:(e,t,n)=>pe(e,t,Gv(n)),closeDisclosure:e=>MW(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>$K(t.activeSegment,e,n,a,r.drawnAt())};return CK(e.kind).render(e,c)},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 "${dS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=XG(pe(me,XU,Uv(S))).map(({line:e,row:t})=>{let n=lW(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...eF(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||kq(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:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}function Mq(e){return Math.max(1,e-2)}function Nq(e,t){return e.kind===`absent`?I(`none`):e.kind===`failed`?e:t.kind===`failed`?t:I(t.kind===`ok`?`tracked`:`gone`)}function Pq(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?R(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const Fq={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},Iq={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Lq(e,t,n){return Object.hasOwn(t,n)?I(t[n]):R(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const Rq={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function zq(e){return Object.keys(Rq).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${Rq[t]}: ${n.reason}`]:[]})}function Bq(e,t,n){return t.ok?I(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?L:R(Vq(e,t),`read`)}function Vq(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Hq(t.stderr)].filter(Boolean).join(`, `)}`}function Hq(e){return e.trim().split(`
|
|
185
|
+
`,1)[0]??``}function Uq(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?L:I(n)}function Wq(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?I(t):L}const Gq={github:`gh`,gitlab:`glab`};function Kq(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const qq=/^[A-Za-z]:[\\/]/;function Jq(e){let t=e.trim();if(qq.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 Yq(e){return Jq(e)?.host||null}function Xq(e){let t=Yq(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const Zq=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function Qq(e){let t=Bq(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?$q(t.value):[]}}function $q(e){let t=new Map;for(let n of e.split(`
|
|
186
|
+
`)){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 eJ(e){return e.urls.find(e=>aJ(e)!==null)??e.urls[0]??null}function tJ(e){return e.find(e=>e.name===`origin`)??e[0]??null}function nJ(e){let t=tJ(e);return t?eJ(t):null}function rJ(e){let t=tJ(e);return t?t.urls.find(e=>Xq(e)!==null)??eJ(t):null}function iJ(e){let t=(Jq(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function aJ(e){let t=Jq(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 oJ(e){let t=nJ(e);return t===null?null:aJ(t)}function sJ(e,t,n,r){return t.ok?r(t.stdout):Kq(t)||t.reason===`non-zero`&&n.test(t.stderr)?L:R(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Hq(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function cJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lJ(e){let t=`detached`,n=L,r=L,i=L,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
187
|
+
`)){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)`?L:I(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=I(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=I({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 uJ(e){let t;try{t=JSON.parse(e)}catch(e){return R(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!cJ(t))return R(`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 R(`gh pr view: missing number/state/url/headRefOid`,`parse`);let o=Lq(`gh pr view`,Fq,r);return o.kind===`ok`?I({number:n,state:o.value,url:i,head:a}):o}function dJ(e){let t;try{t=JSON.parse(e)}catch(e){return R(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!cJ(t))return R(`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 R(`glab mr view: missing iid/state/web_url/sha`,`parse`);let o=Lq(`glab mr view`,Iq,r);return o.kind===`ok`?I({number:n,state:o.value,url:i,head:a}):o}function fJ(e){try{let t=s.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var pJ=class{constructor(e){this.launcher=e}isGitRepo(e){return jc(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)?I(e):t&&this.isGitRepo(t)?I(t):this.isGitRepo(e)?I(e):this.findGitRoot(e)}findGitRoot(e){let t=Mc(e);return t===void 0?L:I(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return R(`git: ${e instanceof Error?e.message:String(e)}`,`read`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=Uq(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=Uq(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=Uq(s,oJ)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),I(o)}resolveGitDir(e){return Oo(Lc(e),T.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return s.existsSync(T.join(t,`MERGE_HEAD`))?I(`MERGE`):s.existsSync(T.join(t,`CHERRY_PICK_HEAD`))?I(`CHERRY-PICK`):s.existsSync(T.join(t,`REVERT_HEAD`))?I(`REVERT`):s.existsSync(T.join(t,`BISECT_LOG`))?I(`BISECT`):s.existsSync(T.join(t,`rebase-merge`))||s.existsSync(T.join(t,`rebase-apply`))?I(`REBASE`):L}catch(e){return R(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async getNearestTagAsync(e){return Wq(Bq(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}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=Wq(Bq(`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)?R(`git log -1: unparseable timestamp "${n.value}"`,`parse`):I(r)}resolveCommonGitDir(e){return Oo(Rc(e),e)}getStashCount(e){let t=T.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=s.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?I(0):R(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return I(r?r.split(`
|
|
188
|
+
`).length:0)}async getRemotesAsync(e){let t=fJ(T.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 Qq(await this.execGitAsync(Zq,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=nJ(e);return(n===null?null:iJ(n))??T.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=rJ(t.value);return n===null?L:I(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=Xq(t);return n===`github`?sJ(`gh pr view`,await this.execForgeAsync(Gq.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,uJ):n===`gitlab`?sJ(`glab mr view`,await this.execForgeAsync(Gq.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,dJ):L}isWorktree(e){try{let t=T.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=Bq(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?I(lJ(t.value)):t}};const mJ=`#/definitions/LayoutNode`,hJ={kind:`container`,direction:`vertical`,children:[]};function gJ(e){return{required:!0,json:{const:e},parse:()=>e}}function _J(){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 ${kb(i)}`,line:J(e.source,[`root`])}),``)}}}function vJ(){return{required:!0,json:{enum:[...Ny]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Ny.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Ny.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function yJ(e){return{required:!0,json:{type:`array`,items:{$ref:mJ}},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 ${Ob(a)}`,line:J(t.source,[`root`])}),[])}}}const bJ={noun:`layout-node key`,fields:{kind:gJ(`segment`),name:_J(),when:Vb(),id:KB(),settings:qB()}},xJ=()=>Yb(av),SJ={noun:`layout-node key`,fields:{kind:gJ(`container`),direction:vJ(),children:yJ(zb(()=>DJ)),when:Vb(),distribution:xJ()}};function CJ(){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 ${kb(i)}`,line:J(e.source,[...t.split(`.`),n])}),``)}}}const wJ={noun:`layout-node key`,fields:{seg:CJ(),when:Vb(),id:KB(),settings:qB()}},TJ={noun:`layout-node key`,fields:{h:yJ(zb(()=>DJ)),when:Vb(),distribution:xJ()}},EJ={noun:`layout-node key`,fields:{v:yJ(zb(()=>DJ)),when:Vb(),distribution:xJ()}},DJ=(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:J(e.source,[`root`])}),hJ):{kind:`segment`,name:n};if(!Db(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 ${Ob(n)}`,line:J(e.source,[`root`])}),hJ;if(n.kind===`container`)return Ab(e,SJ,t,n)??hJ;if(n.kind===`segment`)return Ab(e,bJ,t,n)??hJ;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
189
189
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
190
|
-
New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),mJ;if(n.kind===`group`){let r=Ab(e,FJ,t,n);return r===null?mJ:(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}),LJ(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:J(e.source,[`root`])}),mJ}if(a){let r=Ab(e,CJ,t,n);return r===null?mJ:{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=Ab(e,wJ,t,n);return r===null?mJ:{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=Ab(e,TJ,t,n);return r===null?mJ:{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:J(e.source,[`root`])}),mJ};function DJ(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Xx.source},additionalProperties:{$ref:pJ}},parse:(e,t,n,r)=>{let i=r[n];if(!Db(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Ob(i)}`,line:J(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:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=EJ(e,`${t}.${n}.${r}`,o)}return a}}}const OJ={noun:`root key`,fields:{rows:DJ(),when:Vb(),distribution:bJ()}};function kJ(e,t,n){return Db(n)&&`rows`in n?Ab(e,OJ,t,n)??{rows:{}}:EJ(e,t,n)}const AJ={noun:`insert key`,fields:{seg:SJ(),id:GB(),before:Vb(),after:Vb()}};function jJ(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Ab(e,AJ,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:J(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:J(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:J(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 ${Ob(t)}`,line:J(e.source,[`insert`])}),[])}function MJ(){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 "${P}", got ${kb(i)}`,line:J(e.source,[`root`])});return}return i}}}function NJ(){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 ${kb(i)}`,line:J(e.source,[`root`])});return}return i}}}}function PJ(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Sb(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:J(e.source,[...t.split(`.`),n])});return}return i}}}}const FJ={noun:`layout-node key`,fields:{kind:hJ(`group`),name:MJ(),label:PJ(),open:Hb(),direction:Yb(Ny),key:NJ(),bg:Vb(),fg:Vb(),when:Vb(),distribution:bJ(),children:vJ(zb(()=>EJ))}};function IJ(e){return e.key??`groups.`+e.name}function LJ(e){let t=ji+e.name;return Si(t,{variable:t,key:IJ(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function RJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function zJ(e,t){RN(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)&&RJ(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}.`)&&IJ(t)===IJ(r)&&RJ(e,t.path,`group "${t.name}" shares key "${IJ(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=IJ(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&RJ(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=IJ(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 BJ=`menu`,VJ=`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`,HJ=e=>e.kind===`call`&&e.name===`dict`,UJ=e=>e.kind===`literal`&&typeof e.value!=`object`,WJ=e=>yi(``,e,2)===void 0;function GJ(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&&HJ(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(HJ))return t(`whose options (dict …) is not its last argument — ${VJ}`);if(i!==void 0&&a===void 0&&!UJ(i)&&WJ(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} — ${VJ}`);let c=a===void 0?{}:DD(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=MM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=LN(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 "${EM(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 KJ(e){let t=IT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===BJ).map(GJ)}catch{return`parse-failed`}}function qJ(e,t){let n=KJ(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:TM(t,e.apply,e.options.key),member:wM(e.apply)}]:[])}function JJ(e){let t=IT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(BJ)}catch{return!1}}function YJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function XJ(e,t){RN(e,t,Mi,`{{ menu }} helpers`),RN(e,t,Ni,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))JJ(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:J(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`&&JJ(i)&&YJ(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??{}))JJ(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:J(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of zy(tS(t.root)))typeof n.when==`string`&&JJ(n.when)&&YJ(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||!JJ(r))continue;let n=KJ(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:ZJ(r.apply);n!==void 0&&YJ(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function ZJ(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(wM(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function QJ(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 fS(e.presets)){let a=new Map,s=new Map;for(let c of zy(hS(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,KJ(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Fy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||ZJ(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=wM(i),f=TM(u,i,l.key),p=OM(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=DM(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,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function $J(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const eY={noun:`style key`,fields:{hueShift:Wb(),chromaScale:Wb({min:0}),lightnessScale:Wb(),lightnessShift:Wb()}};function tY(e,t){if(!Db(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Ob(t)}`,line:J(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:J(e.source,[`styles`,r])});continue}if(xy(r)){e.issues.push({path:`styles.${r}`,message:$J(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=Ab(e,eY,`styles.${r}`,i);t!==null&&(n[r]={...Fu,...t})}return n}const nY={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:kJ(e,`${t}.${n}`,r[n])},globals:{required:!1,json:hN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:mN(e,`${t}.${n}`,r[n])}}};function rY(e,t){if(!Db(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Ob(t)}`,line:J(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:J(e.source,[`presets`,r])});continue}let t=Ab(e,nY,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function iY(e,t){let n=[...t].map(([e,t])=>[PS(e),t]);return t=>{if($L(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=IS(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function aY(e){return e.kind===`plugin`||e.kind===`missing`}function oY(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>Qx(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 zy(e))t.kind===`segment`&&i(Fy(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 sY(e){let t=0,n=iY(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)?[Ry(e,i)]:[],o=e=>a(e)[0]??cY,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>Qx(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 cY={kind:`container`,direction:`horizontal`,children:[]},lY={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 uY(e,t){let n=new Map;for(let e of Object.keys(t)){let t=CM(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:J(e.source,[`presets`])})}function dY(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 nS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const fY=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${NS(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${pY(NS(r.definition),n)}${mY(t,n)}`:`${e} entry "${t}" does not match any declared segment${mY(t,n)}`;function pY(e,t){let n=Object.keys(t).filter(PS(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 mY(e,t){return Vz(e)+LS(e,e=>Object.hasOwn(t,e))}function hY(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||ry(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:xy(r)?$J(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:J(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:J(e.source,[`globals`,`preset`])}),uY(e,t.presets);let a=yC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(vY)||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:J(e.source,[`variables`,t])});let o=(t,n,i)=>{nR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" ${nR(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}),rR(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:lY[a](n),line:i});let o=new Map;for(let e of zy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Fy(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=Ly(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`||Py[e.direction]===`cell`);return Py[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Py[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,By(t,n)]):e.opens===void 0?[]:[[e.opens.body,Vy(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=tS(n),s=Qx(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:lY[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of nS(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(PY(e,`${s}.when`,o.when,a,{line:n}),MY(e,`${s}.when`,o.when,n),NY(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if($L(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);aY(c)&&(d.add(o.name),e.unplaced.push({path:s,message:fY(i,o.name,t.segments,c),line:n})),EY(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`,eS(t.root)]]);for(let e of fS(t.presets)){let{node:n,path:r}=hS(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,J(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Hy(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);aY(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:fY(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}HY(e,t,a,()=>!0)}const gY=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function _Y(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!fS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${fS(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(`, `)})${Vz(i)}`,line:c})},p=new Set(Iy(hS(t,a).node)),m=(r,i)=>{!Bz.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${Vz(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 vY=`settings.`;function yY(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>vY+e)])}}function bY(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:J(e.source,[`segments`,t,`settings`,n])})},a=CY(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of rb(n,SY(n)))i(e,`the defaults do not stand together: ${t}`)}function xY(e){return CY(e).length>0||rb(e,SY(e)).length>0}function SY(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function CY(e){let t=t=>nb(wY(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||nb(wY(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${TY(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 wY(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function TY(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&nb(n)!==void 0).map(([e])=>e)}function EY(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=tb(a),s=`${r}: placement "${Fy(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(`, `)})`:ib(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Jv(a):``}, but it must be ${cb(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])=>ib(o[e],t))||xY(o)))for(let{message:t}of rb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function DY(e,t,n,r,i){for(let[a,o]of Jy(n))PY(e,`${t}.${a}`,o,r,{segCtx:i})}function OY(e,t,n,r,i){if(!(!Ky(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:J(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const kY=`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 AY(e,t,n,r){if(!Ky(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=sq(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${kY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=rq(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}: ${kY}`,line:i(`depends_on`)})})}}function jY(e,t){let n=new Map(gC(t)),r=HG(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=ny.find(e=>yM[e]===n||yM[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${yM[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=BG(e,a),s=o===void 0?void 0:bM(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 aq(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:J(e.source,[...n])})}}function MY(e,t,n,r){try{IN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function NY(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 rC(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){IY(e,u,`Template references unknown action "${c}"${r}`,FY(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function PY(e,t,n,r,i){let a=(n,r)=>{if(r!==null){IY(e,r,n,FY(r,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));return}e.issues.push({path:t,message:n,line:i?.line??J(e.source,t.split(`.`))})};for(let[e,t]of $S(n,r.helpers)){if(vC(e,r))continue;if(e.startsWith(vY)){let n=t===null?``:` through helper "${t}"`,r=e.slice(9);a(i?.segCtx===void 0||i.settings===void 0?`Template reads ".${e}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${e}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`,null);continue}let n=i?.segCtx!==void 0&&t===null?`${i.segCtx}.${e}`:void 0;a(`Template references unknown variable ".${e}"${n!==void 0&&vC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Qz(e)}`,t)}for(let{verb:e,via:t}of aC(n,r.helpers)){let n=iB(e);n!==void 0&&a(n,t)}}function FY(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function IY(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:J(e.source,r)})}function LY(e,t,n,r,i){let a=n.set,o=QM(Px[r].configKey),s=`${a} takes ${FM(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:J(e.source,[`actions`,t,`min`])});return}let c=BY(n,i);if(c===zY){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:J(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!PM(o,e.value,i));if(l.length!==0){if(a===Px.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>xy(e.value)))){let r=Px.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:$J(`actions.${t}.to`,n.to,`set: "${r}", to`),line:J(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:J(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<=RY?r.join(`, `):`${r.slice(0,RY).join(`, `)} and ${r.length-RY} 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:J(e.source,[`actions`,t,n])})}}}const RY=3,zY=Symbol(`any integer`);function BY(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?wS(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)}]:zY}function VY(e,t){return Object.entries(e).filter(([e])=>t(e))}function HY(e,t,n,r){let i=AR(t),a=CS(i);for(let[n,o]of VY(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:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;nte.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:J(e.source,[`actions`,n,`set`])});let s=Vx.get(o.set);s!==void 0&&LY(e,n,o,s,i)}for(let[n,i]of VY(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&&jS(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:J(e.source,[`actions`,n,`do`])})});for(let[n,i]of VY(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:J(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of VY(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=jN(r);if(o===null){let t=yN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${bN().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:J(e.source,[`actions`,n,a])});continue}let s=gY.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:J(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){_Y(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!fS(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: ${fS(t.presets).join(`, `)})`,line:J(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${Jv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:J(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(`, `)})${Vz(o.segment)}`,line:J(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:J(e.source,[`actions`,n,a])})}}for(let[i,a]of VY(t.variables,r)){DY(e,`variables.${i}`,a,n);let t=Zz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of VY(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))DY(e,`segments.${i}.vars.${t}`,r,n,i);let r=tb(a);if(bY(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:J(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=yY({...n,helpers:o},r);for(let n of xH){let c=a[n];typeof c==`string`&&(PY(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),NY(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of VY(t.variables,r))OY(e,`variables.${i}`,a,n),AY(e,`variables.${i}`,a,t);jY(e,t);for(let[i,a]of VY(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))OY(e,`segments.${i}.vars.${r}`,o,n,i),AY(e,`segments.${i}.vars.${r}`,o,t)}function UY(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=WY(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:J(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function WY(e){let t=new Map,n=new Map,r=HG(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 GY(e,t,n){let r=new Map([...hC(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, or a control the bar builds), 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:J(e.source,[...d])})}}}function KY(e){return{...tX,config:Iz(tX.raw,e)}}function qY(e,t,n,r,i){let a=cX(e,t,i,(t,a)=>{let o=lH(cH(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>$Y(t,n,r,e,i)),s=pH(o,r.beneath.dropped);return{inherited:new Set([...qB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=mH(Iz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map($V)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const JY=new WeakMap;function YY(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,ZY(e.path)])]),a=JY.get(n)??new Map;JY.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=lH(e,t,{config:n,rendering:new Map},(e,t,n)=>$Y(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function XY(e,t,n,r){return lH(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>$Y(e,t,n,`<plugin install>`,void 0)).dropped}function ZY(e){try{let t=s.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function QY(e,t,n,r,i,a=e=>s.readFileSync(e,`utf-8`),o){let c={repo:i.repo,checkout:i.cwd===null?null:Nc(i.cwd),home:e.home},l=zH(e,c.repo),u=YY(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=qY(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($V));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(nX(KY(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(nX(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())nX(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function $Y(e,t,n,r,i){if(n){nX(eX(e),new Map,r,i);return}let a=PS(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(HY(s,e,yC(e),a),UY(s,e,a),GY(s,e,{checked:a,authored:a}),o.length>0)throw new db(r,o)}function eX(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const tX={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function nX(e,t,n=`<config>`,r=new Set(Zv()),i=[]){let a=iY(e.config.segments,t),o=iX({...e,path:n},i,a),s=(t,s)=>{let c=gS(e.config,t,o.authored);return rX(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof db)||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 db))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,_S(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function rX({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 db(n,[...l,...u.unplaced,...u.inherited],c)};hY(u,a,e,o),UY(u,a),d();let f=oX(n,a.segments,u,o,i,s),p=QJ(sY(a),l);d();let m=QR(mR(p)),h=new Set([...hC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return GY(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function iX(e,t,n){let r=[...t].reverse().concat(e),i=oY(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>aY(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:fY(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function aX(e){if(e.length>0)throw new pb(e)}function oX(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=dY(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:fY(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new fb(e,t))}function sX(e,t,n=new Set(Zv()),r=lX){return cX(e,t,n,()=>({inherited:r,layer:null})).raw}function cX(e,t,n,r){let i=uX(e,t),a=bb(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Zv()),groups:[],unplaced:[],inherited:[]};if(!Db(i))throw new db(e,[{path:``,message:`Config root must be an object, got ${Ob(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:pX({...c,issues:[]},i.plugins)??[],Db(i.segments)?Object.keys(i.segments):[]),d=dX(c,i,l,cV(e),e);if(s.length>0)throw new db(e,s,o);return{raw:d,warnings:o,layer:u}}const lX=new Set;function uX(e,t){try{return Ia.default.parse(t)}catch(t){let n=t;throw new db(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function dX(e,t,n,r,i){for(let n of Object.keys(t))fX.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...fX].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=pN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=aB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=JB(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.
|
|
190
|
+
New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),hJ;if(n.kind===`group`){let r=Ab(e,IJ,t,n);return r===null?hJ:(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}),RJ(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:J(e.source,[`root`])}),hJ}if(a){let r=Ab(e,wJ,t,n);return r===null?hJ:{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=Ab(e,TJ,t,n);return r===null?hJ:{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=Ab(e,EJ,t,n);return r===null?hJ:{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:J(e.source,[`root`])}),hJ};function OJ(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Zx.source},additionalProperties:{$ref:mJ}},parse:(e,t,n,r)=>{let i=r[n];if(!Db(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Ob(i)}`,line:J(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:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=DJ(e,`${t}.${n}.${r}`,o)}return a}}}const kJ={noun:`root key`,fields:{rows:OJ(),when:Vb(),distribution:xJ()}};function AJ(e,t,n){return Db(n)&&`rows`in n?Ab(e,kJ,t,n)??{rows:{}}:DJ(e,t,n)}const jJ={noun:`insert key`,fields:{seg:CJ(),id:KB(),before:Vb(),after:Vb()}};function MJ(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Ab(e,jJ,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:J(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:J(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:J(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 ${Ob(t)}`,line:J(e.source,[`insert`])}),[])}function NJ(){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 "${P}", got ${kb(i)}`,line:J(e.source,[`root`])});return}return i}}}function PJ(){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 ${kb(i)}`,line:J(e.source,[`root`])});return}return i}}}}function FJ(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Sb(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:J(e.source,[...t.split(`.`),n])});return}return i}}}}const IJ={noun:`layout-node key`,fields:{kind:gJ(`group`),name:NJ(),label:FJ(),open:Hb(),direction:Yb(Ny),key:PJ(),bg:Vb(),fg:Vb(),when:Vb(),distribution:xJ(),children:yJ(zb(()=>DJ))}};function LJ(e){return e.key??`groups.`+e.name}function RJ(e){let t=ji+e.name;return Si(t,{variable:t,key:LJ(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function zJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function BJ(e,t){zN(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)&&zJ(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}.`)&&LJ(t)===LJ(r)&&zJ(e,t.path,`group "${t.name}" shares key "${LJ(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=LJ(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&zJ(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=LJ(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 VJ=`menu`,HJ=`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`,UJ=e=>e.kind===`call`&&e.name===`dict`,WJ=e=>e.kind===`literal`&&typeof e.value!=`object`,GJ=e=>yi(``,e,2)===void 0;function KJ(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&&UJ(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(UJ))return t(`whose options (dict …) is not its last argument — ${HJ}`);if(i!==void 0&&a===void 0&&!WJ(i)&&GJ(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} — ${HJ}`);let c=a===void 0?{}:OD(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=NM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=RN(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 "${DM(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 qJ(e){let t=LT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===VJ).map(KJ)}catch{return`parse-failed`}}function JJ(e,t){let n=qJ(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:EM(t,e.apply,e.options.key),member:TM(e.apply)}]:[])}function YJ(e){let t=LT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(VJ)}catch{return!1}}function XJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function ZJ(e,t){zN(e,t,Mi,`{{ menu }} helpers`),zN(e,t,Ni,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))YJ(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:J(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`&&YJ(i)&&XJ(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??{}))YJ(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:J(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of zy(nS(t.root)))typeof n.when==`string`&&YJ(n.when)&&XJ(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||!YJ(r))continue;let n=qJ(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:QJ(r.apply);n!==void 0&&XJ(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function QJ(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(TM(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function $J(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 pS(e.presets)){let a=new Map,s=new Map;for(let c of zy(gS(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,qJ(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Fy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||QJ(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=TM(i),f=EM(u,i,l.key),p=kM(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=OM(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,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function eY(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const tY={noun:`style key`,fields:{hueShift:Wb(),chromaScale:Wb({min:0}),lightnessScale:Wb(),lightnessShift:Wb()}};function nY(e,t){if(!Db(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Ob(t)}`,line:J(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:J(e.source,[`styles`,r])});continue}if(xy(r)){e.issues.push({path:`styles.${r}`,message:eY(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=Ab(e,tY,`styles.${r}`,i);t!==null&&(n[r]={...Fu,...t})}return n}const rY={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:AJ(e,`${t}.${n}`,r[n])},globals:{required:!1,json:gN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:hN(e,`${t}.${n}`,r[n])}}};function iY(e,t){if(!Db(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Ob(t)}`,line:J(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:J(e.source,[`presets`,r])});continue}let t=Ab(e,rY,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function aY(e,t){let n=[...t].map(([e,t])=>[FS(e),t]);return t=>{if($L(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=LS(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function oY(e){return e.kind===`plugin`||e.kind===`missing`}function sY(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 zy(e))t.kind===`segment`&&i(Fy(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 cY(e){let t=0,n=aY(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)?[Ry(e,i)]:[],o=e=>a(e)[0]??lY,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 lY={kind:`container`,direction:`horizontal`,children:[]},uY={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 dY(e,t){let n=new Map;for(let e of Object.keys(t)){let t=wM(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:J(e.source,[`presets`])})}function fY(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 rS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const pY=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${PS(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${mY(PS(r.definition),n)}${hY(t,n)}`:`${e} entry "${t}" does not match any declared segment${hY(t,n)}`;function mY(e,t){let n=Object.keys(t).filter(FS(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 hY(e,t){return Vz(e)+RS(e,e=>Object.hasOwn(t,e))}function gY(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||ry(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:xy(r)?eY(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:J(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:J(e.source,[`globals`,`preset`])}),dY(e,t.presets);let a=bC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(yY)||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:J(e.source,[`variables`,t])});let o=(t,n,i)=>{nR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Li}" ${nR(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}),rR(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:uY[a](n),line:i});let o=new Map;for(let e of zy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Fy(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=Ly(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`||Py[e.direction]===`cell`);return Py[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Py[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,By(t,n)]):e.opens===void 0?[]:[[e.opens.body,Vy(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=nS(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:uY[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of rS(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(FY(e,`${s}.when`,o.when,a,{line:n}),NY(e,`${s}.when`,o.when,n),PY(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if($L(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);oY(c)&&(d.add(o.name),e.unplaced.push({path:s,message:pY(i,o.name,t.segments,c),line:n})),DY(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`,tS(t.root)]]);for(let e of pS(t.presets)){let{node:n,path:r}=gS(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,J(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Hy(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);oY(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:pY(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}UY(e,t,a,()=>!0)}const _Y=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function vY(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!pS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${pS(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(`, `)})${Vz(i)}`,line:c})},p=new Set(Iy(gS(t,a).node)),m=(r,i)=>{!Bz.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${Vz(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 yY=`settings.`;function bY(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>yY+e)])}}function xY(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:J(e.source,[`segments`,t,`settings`,n])})},a=wY(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of rb(n,CY(n)))i(e,`the defaults do not stand together: ${t}`)}function SY(e){return wY(e).length>0||rb(e,CY(e)).length>0}function CY(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function wY(e){let t=t=>nb(TY(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||nb(TY(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${EY(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 TY(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function EY(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&nb(n)!==void 0).map(([e])=>e)}function DY(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=tb(a),s=`${r}: placement "${Fy(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(`, `)})`:ib(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Jv(a):``}, but it must be ${cb(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])=>ib(o[e],t))||SY(o)))for(let{message:t}of rb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function OY(e,t,n,r,i){for(let[a,o]of Jy(n))FY(e,`${t}.${a}`,o,r,{segCtx:i})}function kY(e,t,n,r,i){if(!(!Ky(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:J(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const AY=`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 jY(e,t,n,r){if(!Ky(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=cq(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${AY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=iq(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}: ${AY}`,line:i(`depends_on`)})})}}function MY(e,t){let n=new Map(_C(t)),r=UG(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=ny.find(e=>bM[e]===n||bM[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${bM[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=VG(e,a),s=o===void 0?void 0:xM(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 oq(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:J(e.source,[...n])})}}function NY(e,t,n,r){try{LN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function PY(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 iC(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){LY(e,u,`Template references unknown action "${c}"${r}`,IY(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function FY(e,t,n,r,i){let a=(n,r)=>{if(r!==null){LY(e,r,n,IY(r,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));return}e.issues.push({path:t,message:n,line:i?.line??J(e.source,t.split(`.`))})};for(let[e,t]of eC(n,r.helpers)){if(yC(e,r))continue;if(e.startsWith(yY)){let n=t===null?``:` through helper "${t}"`,r=e.slice(9);a(i?.segCtx===void 0||i.settings===void 0?`Template reads ".${e}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${e}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`,null);continue}let n=i?.segCtx!==void 0&&t===null?`${i.segCtx}.${e}`:void 0;a(`Template references unknown variable ".${e}"${n!==void 0&&yC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Qz(e)}`,t)}for(let{verb:e,via:t}of oC(n,r.helpers)){let n=oB(e);n!==void 0&&a(n,t)}}function IY(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function LY(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:J(e.source,r)})}function RY(e,t,n,r,i){let a=n.set,o=$M(Fx[r].configKey),s=`${a} takes ${IM(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:J(e.source,[`actions`,t,`min`])});return}let c=VY(n,i);if(c===BY){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:J(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!FM(o,e.value,i));if(l.length!==0){if(a===Fx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>xy(e.value)))){let r=Fx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:eY(`actions.${t}.to`,n.to,`set: "${r}", to`),line:J(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:J(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<=zY?r.join(`, `):`${r.slice(0,zY).join(`, `)} and ${r.length-zY} 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:J(e.source,[`actions`,t,n])})}}}const zY=3,BY=Symbol(`any integer`);function VY(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)}]:BY}function HY(e,t){return Object.entries(e).filter(([e])=>t(e))}function UY(e,t,n,r){let i=AR(t),a=wS(i);for(let[n,o]of HY(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:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;tte.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:J(e.source,[`actions`,n,`set`])});let s=Hx.get(o.set);s!==void 0&&RY(e,n,o,s,i)}for(let[n,i]of HY(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&&MS(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:J(e.source,[`actions`,n,`do`])})});for(let[n,i]of HY(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:J(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of HY(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=MN(r);if(o===null){let t=bN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${xN().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:J(e.source,[`actions`,n,a])});continue}let s=_Y.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:J(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){vY(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!pS(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: ${pS(t.presets).join(`, `)})`,line:J(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${Jv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:J(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(`, `)})${Vz(o.segment)}`,line:J(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:J(e.source,[`actions`,n,a])})}}for(let[i,a]of HY(t.variables,r)){OY(e,`variables.${i}`,a,n);let t=Zz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of HY(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))OY(e,`segments.${i}.vars.${t}`,r,n,i);let r=tb(a);if(xY(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:J(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=bY({...n,helpers:o},r);for(let n of SH){let c=a[n];typeof c==`string`&&(FY(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),PY(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of HY(t.variables,r))kY(e,`variables.${i}`,a,n),jY(e,`variables.${i}`,a,t);MY(e,t);for(let[i,a]of HY(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))kY(e,`segments.${i}.vars.${r}`,o,n,i),jY(e,`segments.${i}.vars.${r}`,o,t)}function WY(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=GY(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:J(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function GY(e){let t=new Map,n=new Map,r=UG(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 KY(e,t,n){let r=new Map([...gC(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, or a control the bar builds), 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:J(e.source,[...d])})}}}function qY(e){return{...nX,config:Iz(nX.raw,e)}}function JY(e,t,n,r,i){let a=lX(e,t,i,(t,a)=>{let o=uH(lH(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>eX(t,n,r,e,i)),s=mH(o,r.beneath.dropped);return{inherited:new Set([...JB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=hH(Iz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(eH)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const YY=new WeakMap;function XY(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,QY(e.path)])]),a=YY.get(n)??new Map;YY.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=uH(e,t,{config:n,rendering:new Map},(e,t,n)=>eX(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function ZY(e,t,n,r){return uH(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>eX(e,t,n,`<plugin install>`,void 0)).dropped}function QY(e){try{let t=s.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function $Y(e,t,n,r,i,a=e=>s.readFileSync(e,`utf-8`),o){let c={repo:i.repo,checkout:i.cwd===null?null:Nc(i.cwd),home:e.home},l=BH(e,c.repo),u=XY(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=JY(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(eH));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(rX(qY(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(rX(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())rX(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function eX(e,t,n,r,i){if(n){rX(tX(e),new Map,r,i);return}let a=FS(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(UY(s,e,bC(e),a),WY(s,e,a),KY(s,e,{checked:a,authored:a}),o.length>0)throw new db(r,o)}function tX(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const nX={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function rX(e,t,n=`<config>`,r=new Set(Zv()),i=[]){let a=aY(e.config.segments,t),o=aX({...e,path:n},i,a),s=(t,s)=>{let c=_S(e.config,t,o.authored);return iX(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof db)||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 db))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,vS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function iX({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 db(n,[...l,...u.unplaced,...u.inherited],c)};gY(u,a,e,o),WY(u,a),d();let f=sX(n,a.segments,u,o,i,s),p=$J(cY(a),l);d();let m=QR(mR(p)),h=new Set([...gC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return KY(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function aX(e,t,n){let r=[...t].reverse().concat(e),i=sY(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>oY(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:pY(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function oX(e){if(e.length>0)throw new pb(e)}function sX(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=fY(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:pY(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new fb(e,t))}function cX(e,t,n=new Set(Zv()),r=uX){return lX(e,t,n,()=>({inherited:r,layer:null})).raw}function lX(e,t,n,r){let i=dX(e,t),a=bb(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Zv()),groups:[],unplaced:[],inherited:[]};if(!Db(i))throw new db(e,[{path:``,message:`Config root must be an object, got ${Ob(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:mX({...c,issues:[]},i.plugins)??[],Db(i.segments)?Object.keys(i.segments):[]),d=fX(c,i,l,lV(e),e);if(s.length>0)throw new db(e,s,o);return{raw:d,warnings:o,layer:u}}const uX=new Set;function dX(e,t){try{return Ia.default.parse(t)}catch(t){let n=t;throw new db(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function fX(e,t,n,r,i){for(let n of Object.keys(t))pX.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...pX].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=mN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=sB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=YB(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.
|
|
191
191
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
192
192
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
193
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=kJ(e,`root`,t.root)),t.insert!==void 0&&(a.insert=jJ(e,t.insert,i)),t.actions!==void 0&&(a.actions=oV(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:J(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=tY(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=fN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=rY(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=gN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=aV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=pX(e,t.plugins)),zJ(e,a),XJ(e,a),XN(e,a),RN(e,a,F,`the global settings menu`),zN(e,a,n),a}const fX=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function pX(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 ${Ob(t)}`,line:J(e.source,[`plugins`])})}const mX={},hX=EI(`commands.`),gX=MI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),_X=bI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),vX=`{{ ${pP} }}`,yX={min:0,max:100,step:5},bX={warnAt:{label:`warning at %`,domain:yX,default:50},errorAt:{label:`error at %`,domain:{...yX,atLeast:`warnAt`},default:80}};function xX(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:yX,default:80}}}const SX={globals:{palette:`tokyo-night`},variables:{...hX.variables,...gM,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:`⊫`},..._X.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:vX},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 ${_X.armed} }}{{ if ne .git.branch "" }} {{ end }}${_X.template}{{ end }}`,fg:vX,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:mI(``).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:hX.template,when:hX.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:xX(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:xX(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:bX,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:bX,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) ${Cv} }}`,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:gX.template,bg:gX.bg,when:gX.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:{...mI(``).actions,...hX.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},..._X.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...gX.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:mX,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 ${Cv} }}{{ \$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 (${pP}) 2 (readableOn (color "accent") (bgOf) ${Cv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Cv}) .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:NI(`.`),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 .)) }}`}},CX=new Set([SX.globals.palette,...Object.keys(SX.themeDefaults),...Object.values(SX.segments).map(e=>e.palette)].filter(e=>e!==void 0)),wX=Iz(sX(`<default>`,JSON.stringify(SX),CX),SX),TX=fS(wX.presets);function EX(e){return TX.includes(e)}const DX={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function OX(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function kX(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function AX(e,t,n){return{[kX(Ue(e))]:{...DX,cost:t,input:n}}}function jX(e,t){let n=kX(Ue(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return L;let a={...DX};return r!==void 0&&OX(a,r),i!==void 0&&OX(a,i),I({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})}function MX(e,t,n){return Ut({dir:e.project_dir,env:n===void 0?[]:[[Xo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const NX=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var PX=class{bySession=Y.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:R(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,Y.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};function FX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function IX(e){return{...Object.fromEntries(Ox.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:EX(e.preset)}}}const LX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function RX(e,t){if(!t)return`-`;if(jo(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return jo(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const zX=10*1e3;function BX(e,t){if(!(t<60))return e*3600/t}function VX(e,t,n,r){let i=r-t;if(i<50||i>zX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function HX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=VX(t.input,t.atMs,n.input,n.atMs),i=VX(t.output,t.atMs,n.output,n.atMs),a=VX(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 UX(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>zX)continue;let o=VX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function WX(e,t){let n=vS(e,t),r=[...ny.flatMap(e=>{let t=n[e];return ry(t)?[t]:[]})];for(let n of zy(hS(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...GX(e,n.name));return qX(e,r)}function GX(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 KX(e,t,n){return qX(e,[...GX(e,t),...n])}function qX(e,t){let n=HG(e),r=new Map(gC(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=BG(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function JX(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=WX(e,n);return t.set(n,i),i}}function YX(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function XX(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(LX).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const ZX=new WeakMap;function QX(e){let t=ZX.get(e);return t===void 0&&(t=$X(e),ZX.set(e,t)),t}function $X(e){let t=t=>YX(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function eZ(e){return jq(e.termCols??120)}function tZ(e,t){return $o(Qo(e.claudeConfigDir,t))}function nZ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function rZ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=QX(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=i.clock.monotonic();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${x(t)}`),o=`${e}: ${String(t)}`}n.set(e,A(i.clock,a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today()),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(Ue(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(tZ(a,i.home)))])}function iZ(e,t){return[...t.keys()].filter(t=>e.has(t))}function aZ(e,t){let n=Oj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function oZ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,XX(n),t.workspace?.project_dir]}function sZ(e,t,n,r,i){let a=QX(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return Oj(L);try{return n()}catch(t){return s.push(`${e}: ${x(t)}`),Oj(R(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...oZ(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(iZ(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function cZ(e,t){let{hookData:n,deps:r}=e,i=QX(e.neededInputPaths),a=n.session_id,o=r.lanes(),s=(e,t,n)=>{if(!t)return L;let i=r.faults.of(a,e);if(i!==void 0)return i;try{return n()}catch(t){return r.log(`error`,`${e} read threw: ${x(t)}`),R(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:o.git.current(),usage:s(`session`,i.session,()=>r.usageStore.usageOf(a,n)),context:s(`context`,i.context,()=>r.contextProvider.contextOf(n)),metrics:s(`metrics`,i.metrics,()=>r.metricsProvider.metricsOf(a,n)),activity:s(`activity`,i.activity,()=>r.activityProvider.activityOf(a)),tmuxSession:o.tmux.current(),hostName:o.hostName.current(),hostUser:o.hostUser.current(),cache:s(`cache`,i.cache,()=>r.cacheExpiry.expiryOf(a)),speed:s(`speed`,i.speed,()=>r.usageStore.speedOf(a)),autoCompact:s(`autocompact`,i.autocompact,()=>r.autoCompact.stored(tZ(e.hints,r.home))),sources:new Map([...o.sources].map(([e,t])=>[e,t.current()]))},today:s(`today`,i.today,()=>lZ(o.today,r.usageStore,a)),gathered:i,declaredSources:[...t.keys()],faults:NX.flatMap(e=>{let t=r.faults.of(a,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function lZ(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:I({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function uZ(e){return[e.git.current(),e.tmux.current(),e.hostName.current(),e.hostUser.current(),...[...e.sources.values()].map(e=>e.current())].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function dZ(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?Ao(t.why):void 0}const fZ=e=>{switch(e.kind){case`pending`:return e;case`absent`:return L;case`ok`:return I(e.value);case`failed`:return R(e.reason,e.failedAt)}};function pZ(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=QX(t.neededInputPaths),u=e.builtins,d={usage:fZ(u.session),context:fZ(u.context),metrics:fZ(u.metrics),activity:fZ(u.activity),cache:fZ(u.cache),speed:fZ(u.speed),autoCompact:fZ(u.autocompact),git:fZ(u.git),pr:fZ(u.pr),tmux:fZ(u.tmux),hostName:fZ(u.hostName),hostUser:fZ(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return Ao(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`?Ao(d.git.why):d.git.kind===`ok`?TZ(d.git.value,d.pr,Ao):void 0,g=d.tmux.kind===`pending`?Ao(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?Ao(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?Ao(d.hostUser.why):p(d.hostUser),y=dZ(l.autocompact?d.context:void 0)??bZ(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=l.burn?dZ(d.usage,d.metrics)??gZ(p(d.usage)?.session.cost,p(d.metrics)?.sessionDuration):void 0,C=f(d.speed,_Z),ee=f(d.usage,e=>CZ({cost:e.session.cost,tokens:e.session.tokens})),w=f(d.metrics,e=>CZ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=f(d.activity,xZ),ne=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),T=f(d.cache,e=>({expiresAt:e})),re=wZ(t.home),E=r.workspace?{...r.workspace,current_dir:wZ(r.workspace.current_dir)??``,project_dir:wZ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>wZ(e)??e)}:r.workspace,D=r.session_id;return{...r,...E!==void 0&&{workspace:E},...re!==void 0&&{home:re},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:wZ(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}},...IX(a),history:n.history,navigation:{back:n.back},term:{cols:eZ(i)},...c,...s!==null&&{configPath:s},resumeCommand:MX(E,D,i.claudeConfigDir),...ee!==void 0&&{session:ee},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...l.block&&b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...T!==void 0&&{cache:T},...ne!==void 0&&{context:ne},...w!==void 0&&{metrics:w},...te!==void 0&&{activity:te},...y!==void 0&&{autocompact:y},...hZ(Object.keys(e.sources),t=>{let n=fZ(e.sources[t]);return n.kind===`pending`?Ao(n.why):n})}}function mZ(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function hZ(e,t){let n=Object.fromEntries(MS.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 gZ(e,t){let n=e!=null&&t!=null?BX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function _Z(e){let t=HX(e),n=UX(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function vZ(e,t){if(e.kind===`pending`)return Ao(e.why);if(e.kind!==`ok`)return;let n=jX(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function yZ(e,t,n){await rZ(e,t,n),await Ej(()=>{let t=uZ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function bZ(e,t){switch(e.kind){case`pending`:return Ao(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return jI(e.value,t)}}function xZ(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=SZ(e.running),i=SZ(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 SZ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function CZ(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 wZ(e){return e===void 0||e.length===0||T.sep!==`\\`?e:e.replace(/\\/g,`/`)}function TZ(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=e.upstream===void 0?void 0:r(Mq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Nq(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},...e.workingTree!==void 0&&{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 EZ=Object.freeze({});function DZ(e,t){return e.kind===`decided`?t[e.name]??EZ:EZ}function OZ(e,t){return{...e,...Object.fromEntries(kx.map(n=>[n,e[n]??t[n]]))}}const kZ=(e,t)=>ux(n=>{let{setting:r,on:i,inTmux:a}=rx[n].switch;return e[r]===i&&(t||!a)});function AZ(e,t,n,r){let i=Ax(e);return Xv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function jZ(e,t){return pS(t(`preset`),e.globals.preset,e.presets)}function MZ(e,t,n){let r=jZ(e,t),i=vS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=ite(a.palette,t(`theme`),i.palette),s=OZ(i,DZ(o,e.themeDefaults));return{...Object.fromEntries(Ox.map(e=>[e,AZ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:cy(a.style,t(`style`),s.style,e.styles),effect:vy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const NZ={moving:1e3/30,still:1e3},PZ=[`data`,`state`,`reload`,`visibility`];function FZ(e){return ix.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 IZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const LZ=(e,t)=>rx[t].handsOff?e.resp:e.statusline,RZ=e=>Math.round(1e3/e);var zZ=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)}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 dx;let r=t-1,i=this.shown(n);return ux(e=>{let a=n.rates.get(e);if(a===void 0)return cx;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,RZ(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||LZ(a,t)!==LZ(i,t))&&IZ(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=LZ(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:XM(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=Pj.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=${RZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${PZ.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 BZ(e,t){return ix.filter(n=>e[n]&&rx[n].handsOff&&t.has(n))}function VZ(e,t){return{severity:hU,lines:[[gU(`[⟲ claude]`,Ta([{verb:ta,args:[e,...t.map(e=>rx[e].switch.setting)]}]))]]}}function HZ(e,t){for(let n of Object.entries(t))e.push(n)}const UZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function WZ(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 GZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...WZ(n)];return{level:UZ[n.kind],line:KZ(e,i)}}const KZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`,qZ=()=>{},JZ=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),YZ={ansi:e=>({ok:!0,output:Dte(e)}),frame:e=>({ok:!0,frame:e})};function XZ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=No();let i=c.u(nQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=iQ(e,i,{by:`feed`,fps:n}),p=YZ.ansi(o.body),m=dQ(t,o,BZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:YZ.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}=GZ(`render`,s,{kind:`threw`,error:e},A(i,o)),r=JZ(e);return{bar:xte(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:qZ,failure:{level:t,line:`frame ${n}`}}}}function ZZ(e,t,n){let{sessionState:r}=e;return MZ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function QZ(e,t){try{var n=No();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:kZ(i.view.source.effective(),Wc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function $Z(e,t,n){try{var r=No();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return kZ(ZZ(e,n,o.state),s===null||Wc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function eQ(e,t,n){HZ(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Vn(e,r),a=Hn(i);return HZ(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function tQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&T.isAbsolute(a)&&{location:Hc(a)}}},s=eQ(o,n,r);HZ(r,{encoding:o.encoding});let c=o.requested;return rQ(e,i.holdSession(c.projectDir,c.cwd,c.target.path,o),o,s,n,r)}function nQ(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{s=eQ(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return rQ(e,a,o,s,n,r)}function rQ(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function iQ(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(),ee=b.source.failure(),w=kZ(C,S.tmux!==void 0);HZ(g,{lanes:ix.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;HZ(g,{width:String(ne)});let T=Tc(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({sessionId:_,dismissed:r.get(_,jz),enabled:C.updateNotice}),D=UU(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Wn(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(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:lj(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...al(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=_U(_,n.by,ae,[...E,...D],[...ue.map(e=>({about:e.kind,message:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),pe=b.source.facts(),me={diagnostics:DU(fe),drawing:n,feeds:i.feedsOf(_,h),today:vZ(pe.builtins.today,h)},he=jo(S.metrics)?void 0:S.metrics;HZ(g,mZ(pe.sources)),HZ(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:RX(S.git,XX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:FZ(me.feeds)});let ge=[],_e=FX(C,ne),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=Aq(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=yU(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);HZ(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:kU(te.termRows,n.by===`feed`?ix.flatMap(e=>{let t=rx[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=OU(r.get(_,Bi),fe),je=Ae===null?be:IP(be,AU(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(`,`)||`-`,Ie=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}},A=[...ue,...ge].map(Ie).join(`,`)||`-`;return HZ(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:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.length),ask:String(D.length),warn:A,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:re,pipeShown:le,delivered:Ee,lanes:w}}function aQ(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,KU,o);let s=WU(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,GU,s)}async function oQ(e,t,n,r,i){return aQ(e,t),uQ(e,t,n,r,i)}function sQ(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(cQ(t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function cQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:eF(e.hookData)}}function lQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:cQ(s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function uQ(e,t,n,r,i){try{var a=No();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(tQ(e,t,n,i));sQ(e,t,kZ(l.view.source.effective(),Wc(t.hints.tmux)));let u=o.monotonic(),d=r-u;HZ(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await Dj(e=>Promise.all([yZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();HZ(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:nZ(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=iQ(e,l,ox),b=t.sessionId,S=BZ(y,s.following(b)),C=tF(t.hints.client??null)===`statusline`,ee=YZ[t.encoding](C?dQ(b,h,S):h.body);return HZ(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{resp:ee,motion:h.body.motion,clickShown:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function dQ(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:IP(t.body,jU(VZ(e,[r,...i]),t.diagnostics,e,t.geometry))}const fQ=/^─{20,}/,pQ=/^❯(\s|$)/,mQ=/›\s*stashed$/;function hQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>fQ.test(e)?[t]:[]).at(-2);return n===void 0||!pQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function gQ(e){if(e.inMode)return{kind:`in-mode`};let t=hQ(e);return t===null?{kind:`no-prompt`}:mQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function _Q(e){return/^❯\s*\S/u.test(hQ(e)?.prompt??``)}const vQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function yQ(e){return e.screen.some(e=>vQ.test(e))}const bQ={"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 xQ(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 SQ(e,t,n){let r=gQ(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:bQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function CQ(e,t,n,r,i){let a=await bc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function wQ(e,t){let n=await CQ(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(`
|
|
194
|
-
`);return{inMode:r!==`0`,screen:i}}function TQ(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 EQ(e,t,n){let r=await CQ(e,t,`claude-input.type`,TQ(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 DQ(e){return{read:t=>wQ(e,t),type:(t,n)=>EQ(e,t,n)}}const OQ={kind:`ok`,said:``},kQ=e=>({kind:`failed`,said:e}),AQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`};function jQ(e){let t=AQ[e.kind];return t(e)}var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},MQ=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},NQ=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function PQ(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}function FQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Dy:Oy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const IQ=Object.entries(Px),LQ=new Set(Ix.map(e=>e.sessionKey)),RQ=()=>!1;function zQ(e,t){return MZ(e,e=>LQ.has(e)?t(e):null,RQ)}const BQ=[`preset`,`theme`];function VQ(e,t,n){let r=new Set(BQ.slice(0,n).map(e=>Px[e].sessionKey));return MZ(e,e=>r.has(e)?t(e):null,RQ)}function HQ(e,t){let n=Array.from({length:BQ.length+1},(n,r)=>VQ(e,t,r));return e=>{let t=BQ.indexOf(e);return n[t===-1?BQ.length:t]}}function UQ(e,t,n,r){return e.flatMap(([e,i])=>{let a=FQ(t,e);return a===null||a===FQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function WQ(e,t,n){return FQ(zQ(e,t),n)}function GQ(e,t){let n=zQ(e,t);return UQ(IQ,n,HQ(e,t),t=>KQ(e,n.preset,t.configKey))}function KQ(e,t,n){return n in(mS(e.presets,t).globals??{})?AN(t,n):n}function qQ(e,t,n){let r=pS(t(Px.preset.sessionKey),e.globals.preset,e.presets),i=jN(n);return{key:i?.scope===`globals`?KQ(e,r,i.field):n,globals:vS(e,r)}}function JQ(e,t){let{preset:n}=zQ(e,t);return ZQ(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:ob(a,s);return c===void 0||ab(c)===ab(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function YQ(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return fS(e.presets).flatMap(n=>{let i=ZQ(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 rb(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:ob(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const XQ=new WeakMap;function ZQ(e,t){let n=XQ.get(e)??new Map;XQ.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...zy(hS(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=tb(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 QQ(e,t){let n=zQ(e,t);return{from:n.preset,globals:mS(e.presets,n.preset).globals??{},picks:UQ(IQ.filter(([e])=>e!==`preset`),n,HQ(e,t),e=>e.configKey),placements:JQ(e,t)}}function $Q(e,t){return MZ({...e,globals:{palette:t},presets:{}},()=>null,RQ)}function e$(e,t){let n=zQ(e,t),r=FQ(n,`theme`);if(r===null)return{kind:`rule`};let i=$Q(e,r),a=vS(e,n.preset),o=Object.fromEntries(kx.map(e=>[e,FQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:kx.some(e=>o[e]!==FQ(i,e))}}function t$(e){return{sessionKeys:Ix.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...cN(e)?TX.map(t=>AN(t,e)):[],...kN(e)?Zv().map(t=>ON(t,e)):[]]}}function n$(e){return new Set(Ix.map(e=>e.configKey).filter(t=>t$(t).fileKeys.some(t=>a$(e,i$(t)))))}function r$(e,t,n){let r=GQ(e,n),i=new Set(r.map(e=>e.configKey)),a=Bx(e=>i.has(Px[e].configKey)||t.has(Px[e].configKey)),o=e$(e,n);return{unsaved:r.length+JQ(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function i$(e){let t=jN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return MN(t)}function a$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&a$(e[n],r)}function o$(e,t,n){let r=Vx.get(n);if(r!==void 0)return WQ(e,t,r);for(let[,t]of Zy(e))if(t.key===n)return t.default??null;return null}function s$(e,t){let n=SN(e).get(t);return n===void 0?null:String(n)}const c$={inside:()=>[],defaultOf:()=>P,menus:[]},l$=e=>`${e.key}\0${e.member}`;function u$(e){let t=new Map,n=n=>{let r=`${n.name}\0${Fy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:qJ(a,Fy(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(l$(e))??new Map;n.set(l$(t),t),o.set(l$(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(l$(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 fS(e.presets))d(hS(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(l$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(l$(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(l$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const d$=new WeakMap;function f$(e){let t=d$.get(e);if(t!==void 0)return t;let n=u$(e);return d$.set(e,n),n}function p$(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 m$(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 h$(e,t,n){let r=(r,i,a)=>{let o=p$(t(r),t=>e.get(r,t),i);(0,Y.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 g$=new Set([`1`,`true`]),_$=new Set([`0`,`false`,``]);function v$(e,t){let n=H$(e),r=n.scope===`segment-palette`?`string`:Mx(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(g$.has(t))return`true`;if(_$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function y$(e){try{return s.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function b$(e,t,n){try{if(t===null){s.rmSync(kn(e),{force:!0});return}On(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function x$(e){return/^\s*$/.test(e)?null:Ua(e)}function S$(e,t){return e!==null&&Ga(e,t)!==void 0}function C$(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(C$),...i}}return e}function w$(e){if(!Qx(e))return C$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,C$(t)])),...n}}const T$=SX,E$=T$.segments,D$=T$.presets,O$=T$.root;function k$(e,t,n,r){if(!S$(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function A$(e,t){let n=MN(t);return t.scope===`segment-palette`&&k$(e,[`segments`,t.segment],E$[t.segment],n.join(`.`)),n}function j$(e){return Ua($a(e))}function M$(){return Object.entries(O$.rows).map(([e,t])=>{let n=C$(t);return{path:[`root`],fragment:j$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function N$(e,t){let n=e===null?void 0:Ga(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function P$(e,t){if(t===void 0)return null;let n=w$(t);return{path:e,fragment:j$(n),unit:{path:e,value:n}}}function F$(e,t){let n=[`presets`,t],r=[...n,`root`],i=D$[t];k$(e,n,i,r.join(`.`));let a=N$(e,r)??P$(r,i?.root);return a!==null&&xo(a.fragment)?a:null}function fne(e,t){let n=bo(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 I$(e,t){return[...M$(),N$(e,[`root`]),F$(e,t)].filter(e=>e!==null).reduce(fne,new Map)}function L$(e,t,n){for(let{node:r,...i}of I$(e,t).values())if(Co(r,n))return i;throw new Z(`${R$(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 R$(e,t){return F$(e,t)?.path??[`root`]}function z$(e,t){return t.scope===`preset-root`?R$(e,t.preset):MN(t)}function B$(e,{unit:t}){return t===null?e:mo(e,t.path,$a(t.value),Za)}function V$(e){let t=jN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function H$(e){let t=V$(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function U$(e,t,n,r,i){let a=e1(t,r),o,s=()=>(o??={chain:J$(t,n)}).chain;t1(t,s,a),i(t,s,a),b$(t.path,r,e.logger),e.record(t.path,n,r)}function W$(e,t,n){let r=q$(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 G$=()=>{};function K$(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 q$(e,t,n){if(t===null)return[];let r=new Set(Q$(Z$(t),Z$(n)));return Q$(X$(e,t),X$(e,n)).filter(e=>!r.has(e))}function J$(e,t){try{return Y$(e,t)}catch(e){if(e instanceof db)return null;throw e}}function Y$(e,t){return QY(e.locs,t===null?e.above:[tU(e.path),...e.above],wX,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:s.readFileSync(n,`utf8`))}function X$(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Z$(e){return e.layers.at(-1)?.config??e.base}function Q$(e,t,n=``){return!$$(e)||!$$(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Q$(e[r],t[r],n===``?r:`${n}.${r}`))}function $$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function e1(e,t){try{return Y$(e,t)}catch(e){throw e instanceof db?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function t1(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 db(e,[t]).message).join(`
|
|
195
|
-
`)}`)}function n1(e,t){let n=H$(t),r=x$(y$(e)??``),i=r===null?void 0:Ga(r,MN(n));return i!==void 0&&`value`in i?i.value:void 0}function r1(e,t,n){i1(e,t,n,[])}function i1(e,t,n,r){let i=y$(t.path),a=n.reduce((e,[t,n])=>mo(e,A$(x$(e),H$(t)),v$(t,n),Za),i??``);U$(e,t,i,K$(t,()=>a1(a,t.path,r,e=>e)),W$)}function a1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=L$(x$(s),n,i),l=Do(B$(s,c),c.path,i,a,$a(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 o1(e,t,n){let r=x$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of I$(r,t)){if(!Co(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qa(e,c):$a(s.value);if(a!==`#`)return mo(e,[...i,`rows`,a],l,Za);if(F$(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 mo(e,i,l,Za)}return e}function s1(e,t){return go(e,t,t[0]===`presets`&&t.length>2&&!EX(t[1])?2:0)}function c1(e,t,n){let r=n.map(V$),i=y$(t.path);if(i===null)return;let a=r.reduce((e,t)=>s1(e,z$(x$(e),t)),i);a!==i&&U$(e,t,i,a,G$)}function l1(e){let t=e===null?void 0:Ga(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function u1(e,t){let n=new Set([...TX,...l1(e),...t.above.flatMap(e=>Object.keys(Ia.default.parse(s.readFileSync(e.path,`utf8`)).presets??{}))].map(CM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(CM(e)))}function d1(e,t,n,r,i,a){let o=y$(t.path),s=x$(o??``),c=u1(s,t),l=[`presets`,c],u=K$(t,()=>F$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qa(o??``,u.fragment):$a(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$a(r)]]],f=i.map(([e,t])=>{let n=AN(c,e);return[A$(s,H$(n)),v$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>mo(e,t,n,Za),mo(o??``,l,`{}`,Za));return U$(e,t,o,K$(t,()=>a1(p,t.path,a.map(e=>({...e,preset:c})),o1)),W$),c}function f1(e,t,n,r){let i=y$(t.path);U$(e,t,i,mo(i??``,[`themeDefaults`,n],$a(r),Za),W$)}function p1(e,t,n){if(EX(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=y$(t.path),a=x$(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`]);U$(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>s1(e,t),i),G$)}function m1(e,t,n,r){let i=V$(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=y$(t.path),o=r.op===`remove`?r.target:r.anchor,s=K$(t,()=>L$(x$(a??``),i.preset,o)),c=B$(a??``,s),{after:l,placed:u}=h1(c,s.path,r,()=>{let e=e1(t,c).config;return fS(e.presets).map(t=>hS(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 U$(e,t,a,l,W$),u}function h1(e,t,n,r){switch(n.op){case`remove`:return{after:To(e,t,n.target),placed:null};case`insert`:{let i=tz(n.segment,n.anchor,r());return{after:Eo(e,t,i,n.anchor,n.relation),placed:i}}}}function g1(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 _1={load:()=>({}),save:()=>{},flush:()=>{}};var v1=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=_1,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Y.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,Y.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,Y.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=_1}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}};const y1={load:()=>({}),save:()=>{}},b1=new Set(Ix.map(e=>e.sessionKey)),x1=e=>b1.has(e)||e.startsWith(WN),S1=8*1024*1024,C1={past:[],future:[]},w1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var T1=class{held=Y.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,Y.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=y1){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??C1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??C1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(w1(r));i.set(w1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:g1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!x1(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:N1(i,r),o=n.get(e),s=o===void 0?a:L1(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`,F1(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(w1)),a=n.net.filter(e=>!i.has(w1(e))),o=O1(R1(I1(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(B1).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=O1(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...A1(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(w1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:R1(n,t),future:R1(i,t),...a!==void 0&&{savepoint:{at:R1([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(w1(e))),below:R1(a.below,t)}}}),new Z(`${r}: ${o.map(B1).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):y$(t.file)}write(e,t,n){t.kind===`file`?b$(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||E1(n)>S1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,D1(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${S1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function E1(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 D1({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...A1(n,1,[])}:{past:e,future:t.slice(1),...A1(n,0,[])}}function O1(e){return e.slice(-50)}const k1=e=>e===KN.member;function A1(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:j1(e.net,n),below:e.below}}}function j1(e,t){let n=new Map(e.map(e=>[w1(e),e]));for(let e of t){let t=n.get(w1(e));n.set(w1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const M1=e=>e.map(e=>({...e,before:e.after,after:e.before}));function N1(e,t){let n=[...e.past,t],r=O1(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...A1(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...P1(e.future,a),...i.below]},n.length-r.length,t)}}function P1(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function F1(e,t){return{past:e.past.slice(0,-1),future:O1([...e.future,t]),...A1(e.savepoint,0,M1(t))}}function I1(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...P1(r,t.at-i.length),...t.below]}function L1(e,t){if(k1(t.after)&&!k1(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!k1(t.after)&&k1(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function R1(e,t){return e.map(e=>e.filter(e=>!t.has(w1(e)))).filter(e=>e.length>0)}function z1(e){return e.map(B1).join(`, `)}function B1(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function V1(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 H1(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(V1))}function U1(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(V1)&&H1(t.below)}function W1(e){if(typeof e!=`object`||!e)return!1;let t=e;return H1(t.past)&&H1(t.future)&&(t.savepoint===void 0||U1(t.savepoint))}function G1(e,t){let n=e=>e.kind===`file`||x1(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 K1(e,t){return{load:()=>{let n;try{n=s.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(W1)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,G1(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{s.mkdirSync(T.dirname(e),{recursive:!0}),On(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 q1=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function J1(e){return{...Object.fromEntries(q1.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 Y1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function X1(e){let t=e=>({kind:`failed`,reason:e});if(!Y1(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!Y1(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!mF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${mF.join(` or `)}`)}return{kind:`ok`,value:e}}function Z1(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Q1=e=>uU(e,`doctor-marks.json`,{},X1),$1=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},e0=(e,t)=>e.includes(t)?e:[...e,t],t0=e=>uU(e,`doctor-clicked-terminals.json`,[],$1);var n0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const r0=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},i0=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),a0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=i0(e,t);return r===void 0?n:r.projectDir},o0=(e,t)=>i0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function s0(e){let t=new Map;for(let n of e.split(`
|
|
196
|
-
`)){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*
|
|
197
|
-
`)){let e=
|
|
193
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=AJ(e,`root`,t.root)),t.insert!==void 0&&(a.insert=MJ(e,t.insert,i)),t.actions!==void 0&&(a.actions=sV(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:J(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=nY(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=pN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=iY(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=_N(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=oV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=mX(e,t.plugins)),BJ(e,a),ZJ(e,a),ZN(e,a),zN(e,a,F,`the global settings menu`),BN(e,a,n),a}const pX=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function mX(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 ${Ob(t)}`,line:J(e.source,[`plugins`])})}const hX={},gX=EI(`commands.`),_X=MI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),vX=bI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),yX=`{{ ${mP} }}`,bX={min:0,max:100,step:5},xX={warnAt:{label:`warning at %`,domain:bX,default:50},errorAt:{label:`error at %`,domain:{...bX,atLeast:`warnAt`},default:80}};function SX(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:bX,default:80}}}const CX={globals:{palette:`tokyo-night`},variables:{...gX.variables,..._M,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:`⊫`},...vX.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:yX},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 ${vX.armed} }}{{ if ne .git.branch "" }} {{ end }}${vX.template}{{ end }}`,fg:yX,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:mI(``).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:gX.template,when:gX.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:SX(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:SX(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:xX,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:xX,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) ${Cv} }}`,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:_X.template,bg:_X.bg,when:_X.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:{...mI(``).actions,...gX.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...vX.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},..._X.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:hX,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 ${Cv} }}{{ \$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 (${mP}) 2 (readableOn (color "accent") (bgOf) ${Cv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Cv}) .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:NI(`.`),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 .)) }}`}},wX=new Set([CX.globals.palette,...Object.keys(CX.themeDefaults),...Object.values(CX.segments).map(e=>e.palette)].filter(e=>e!==void 0)),TX=Iz(cX(`<default>`,JSON.stringify(CX),wX),CX),EX=pS(TX.presets);function DX(e){return EX.includes(e)}const OX={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function kX(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function AX(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function jX(e,t,n){return{[AX(Ue(e))]:{...OX,cost:t,input:n}}}function MX(e,t){let n=AX(Ue(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return L;let a={...OX};return r!==void 0&&kX(a,r),i!==void 0&&kX(a,i),I({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})}function NX(e,t,n){return Ut({dir:e.project_dir,env:n===void 0?[]:[[Xo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const PX=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var FX=class{bySession=Y.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:R(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,Y.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};function IX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function LX(e){return{...Object.fromEntries(kx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:DX(e.preset)}}}const RX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function zX(e,t){if(!t)return`-`;if(jo(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return jo(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const BX=10*1e3;function VX(e,t){if(!(t<60))return e*3600/t}function HX(e,t,n,r){let i=r-t;if(i<50||i>BX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function UX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=HX(t.input,t.atMs,n.input,n.atMs),i=HX(t.output,t.atMs,n.output,n.atMs),a=HX(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 WX(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>BX)continue;let o=HX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function GX(e,t){let n=yS(e,t),r=[...ny.flatMap(e=>{let t=n[e];return ry(t)?[t]:[]})];for(let n of zy(gS(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...KX(e,n.name));return JX(e,r)}function KX(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 qX(e,t,n){return JX(e,[...KX(e,t),...n])}function JX(e,t){let n=UG(e),r=new Map(_C(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=VG(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function YX(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=GX(e,n);return t.set(n,i),i}}function XX(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function ZX(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(RX).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const QX=new WeakMap;function $X(e){let t=QX.get(e);return t===void 0&&(t=eZ(e),QX.set(e,t)),t}function eZ(e){let t=t=>XX(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function tZ(e){return Mq(e.termCols??120)}function nZ(e,t){return $o(Qo(e.claudeConfigDir,t))}function rZ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function iZ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=$X(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=i.clock.monotonic();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${x(t)}`),o=`${e}: ${String(t)}`}n.set(e,A(i.clock,a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today()),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(Ue(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(nZ(a,i.home)))])}function aZ(e,t){return[...t.keys()].filter(t=>e.has(t))}function oZ(e,t){let n=kj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function sZ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,ZX(n),t.workspace?.project_dir]}function cZ(e,t,n,r,i){let a=$X(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return kj(L);try{return n()}catch(t){return s.push(`${e}: ${x(t)}`),kj(R(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...sZ(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(aZ(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function lZ(e,t){let{hookData:n,deps:r}=e,i=$X(e.neededInputPaths),a=n.session_id,o=r.lanes(),s=(e,t,n)=>{if(!t)return L;let i=r.faults.of(a,e);if(i!==void 0)return i;try{return n()}catch(t){return r.log(`error`,`${e} read threw: ${x(t)}`),R(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:o.git.current(),usage:s(`session`,i.session,()=>r.usageStore.usageOf(a,n)),context:s(`context`,i.context,()=>r.contextProvider.contextOf(n)),metrics:s(`metrics`,i.metrics,()=>r.metricsProvider.metricsOf(a,n)),activity:s(`activity`,i.activity,()=>r.activityProvider.activityOf(a)),tmuxSession:o.tmux.current(),hostName:o.hostName.current(),hostUser:o.hostUser.current(),cache:s(`cache`,i.cache,()=>r.cacheExpiry.expiryOf(a)),speed:s(`speed`,i.speed,()=>r.usageStore.speedOf(a)),autoCompact:s(`autocompact`,i.autocompact,()=>r.autoCompact.stored(nZ(e.hints,r.home))),sources:new Map([...o.sources].map(([e,t])=>[e,t.current()]))},today:s(`today`,i.today,()=>uZ(o.today,r.usageStore,a)),gathered:i,declaredSources:[...t.keys()],faults:PX.flatMap(e=>{let t=r.faults.of(a,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function uZ(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:I({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function dZ(e){return[e.git.current(),e.tmux.current(),e.hostName.current(),e.hostUser.current(),...[...e.sources.values()].map(e=>e.current())].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function fZ(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?Ao(t.why):void 0}const pZ=e=>{switch(e.kind){case`pending`:return e;case`absent`:return L;case`ok`:return I(e.value);case`failed`:return R(e.reason,e.failedAt)}};function mZ(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=$X(t.neededInputPaths),u=e.builtins,d={usage:pZ(u.session),context:pZ(u.context),metrics:pZ(u.metrics),activity:pZ(u.activity),cache:pZ(u.cache),speed:pZ(u.speed),autoCompact:pZ(u.autocompact),git:pZ(u.git),pr:pZ(u.pr),tmux:pZ(u.tmux),hostName:pZ(u.hostName),hostUser:pZ(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return Ao(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`?Ao(d.git.why):d.git.kind===`ok`?EZ(d.git.value,d.pr,Ao):void 0,g=d.tmux.kind===`pending`?Ao(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?Ao(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?Ao(d.hostUser.why):p(d.hostUser),y=fZ(l.autocompact?d.context:void 0)??xZ(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=l.burn?fZ(d.usage,d.metrics)??_Z(p(d.usage)?.session.cost,p(d.metrics)?.sessionDuration):void 0,C=f(d.speed,vZ),ee=f(d.usage,e=>wZ({cost:e.session.cost,tokens:e.session.tokens})),w=f(d.metrics,e=>wZ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=f(d.activity,SZ),ne=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),T=f(d.cache,e=>({expiresAt:e})),re=TZ(t.home),E=r.workspace?{...r.workspace,current_dir:TZ(r.workspace.current_dir)??``,project_dir:TZ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>TZ(e)??e)}:r.workspace,D=r.session_id;return{...r,...E!==void 0&&{workspace:E},...re!==void 0&&{home:re},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:TZ(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}},...LX(a),history:n.history,navigation:{back:n.back},term:{cols:tZ(i)},...c,...s!==null&&{configPath:s},resumeCommand:NX(E,D,i.claudeConfigDir),...ee!==void 0&&{session:ee},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...l.block&&b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...T!==void 0&&{cache:T},...ne!==void 0&&{context:ne},...w!==void 0&&{metrics:w},...te!==void 0&&{activity:te},...y!==void 0&&{autocompact:y},...gZ(Object.keys(e.sources),t=>{let n=pZ(e.sources[t]);return n.kind===`pending`?Ao(n.why):n})}}function hZ(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function gZ(e,t){let n=Object.fromEntries(NS.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 _Z(e,t){let n=e!=null&&t!=null?VX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function vZ(e){let t=UX(e),n=WX(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function yZ(e,t){if(e.kind===`pending`)return Ao(e.why);if(e.kind!==`ok`)return;let n=MX(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function bZ(e,t,n){await iZ(e,t,n),await Dj(()=>{let t=dZ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function xZ(e,t){switch(e.kind){case`pending`:return Ao(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return jI(e.value,t)}}function SZ(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=CZ(e.running),i=CZ(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 CZ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function wZ(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 TZ(e){return e===void 0||e.length===0||T.sep!==`\\`?e:e.replace(/\\/g,`/`)}function EZ(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=e.upstream===void 0?void 0:r(Nq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Pq(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},...e.workingTree!==void 0&&{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 DZ=Object.freeze({});function OZ(e,t){return e.kind===`decided`?t[e.name]??DZ:DZ}function kZ(e,t){return{...e,...Object.fromEntries(Ax.map(n=>[n,e[n]??t[n]]))}}const AZ=(e,t)=>ux(n=>{let{setting:r,on:i,inTmux:a}=rx[n].switch;return e[r]===i&&(t||!a)});function jZ(e,t,n,r){let i=jx(e);return Xv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function MZ(e,t){return mS(t(`preset`),e.globals.preset,e.presets)}function NZ(e,t,n){let r=MZ(e,t),i=yS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=rte(a.palette,t(`theme`),i.palette),s=kZ(i,OZ(o,e.themeDefaults));return{...Object.fromEntries(kx.map(e=>[e,jZ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:cy(a.style,t(`style`),s.style,e.styles),effect:vy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const PZ={moving:1e3/30,still:1e3},FZ=[`data`,`state`,`reload`,`visibility`];function IZ(e){return ix.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 LZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const RZ=(e,t)=>rx[t].handsOff?e.resp:e.statusline,zZ=e=>Math.round(1e3/e);var BZ=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)}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 dx;let r=t-1,i=this.shown(n);return ux(e=>{let a=n.rates.get(e);if(a===void 0)return cx;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,zZ(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||RZ(a,t)!==RZ(i,t))&&LZ(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=RZ(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:ZM(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=Fj.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=${zZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${FZ.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 VZ(e,t){return ix.filter(n=>e[n]&&rx[n].handsOff&&t.has(n))}function HZ(e,t){return{severity:gU,lines:[[_U(`[⟲ claude]`,Ta([{verb:ta,args:[e,...t.map(e=>rx[e].switch.setting)]}]))]]}}function UZ(e,t){for(let n of Object.entries(t))e.push(n)}const WZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function GZ(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 KZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...GZ(n)];return{level:WZ[n.kind],line:qZ(e,i)}}const qZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`,JZ=()=>{},YZ=e=>({ok:!1,error:e instanceof Error?e.message:x(e),code:`RENDER_FAILED`,daemonV:3}),XZ={ansi:e=>({ok:!0,output:Ete(e)}),frame:e=>({ok:!0,frame:e})};function ZZ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[];try{try{var c=No();let i=c.u(rQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=aQ(e,i,{by:`feed`,fps:n}),p=XZ.ansi(o.body),m=fQ(t,o,VZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:XZ.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}=KZ(`render`,s,{kind:`threw`,error:e},A(i,o)),r=YZ(e);return{bar:bte(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:JZ,failure:{level:t,line:`frame ${n}`}}}}function QZ(e,t,n){let{sessionState:r}=e;return NZ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function $Z(e,t){try{var n=No();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:AZ(i.view.source.effective(),Wc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function eQ(e,t,n){try{var r=No();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return AZ(QZ(e,n,o.state),s===null||Wc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function tQ(e,t,n){UZ(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Vn(e,r),a=Hn(i);return UZ(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function nQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&T.isAbsolute(a)&&{location:Hc(a)}}},s=tQ(o,n,r);UZ(r,{encoding:o.encoding});let c=o.requested;return iQ(e,i.holdSession(c.projectDir,c.cwd,c.target.path,o),o,s,n,r)}function rQ(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{s=tQ(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return iQ(e,a,o,s,n,r)}function iQ(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function aQ(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(),ee=b.source.failure(),w=AZ(C,S.tmux!==void 0);UZ(g,{lanes:ix.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;UZ(g,{width:String(ne)});let T=Tc(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({sessionId:_,dismissed:r.get(_,jz),enabled:C.updateNotice}),D=WU(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(Wn(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(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:uj(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...al(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=vU(_,n.by,ae,[...E,...D],[...ue.map(e=>({about:e.kind,message:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),pe=b.source.facts(),me={diagnostics:OU(fe),drawing:n,feeds:i.feedsOf(_,h),today:yZ(pe.builtins.today,h)},he=jo(S.metrics)?void 0:S.metrics;UZ(g,hZ(pe.sources)),UZ(g,{prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:zX(S.git,ZX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:IZ(me.feeds)});let ge=[],_e=IX(C,ne),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=jq(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=bU(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);UZ(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:AU(te.termRows,n.by===`feed`?ix.flatMap(e=>{let t=rx[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=kU(r.get(_,Bi),fe),je=Ae===null?be:LP(be,jU(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(`,`)||`-`,Ie=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}},A=[...ue,...ge].map(Ie).join(`,`)||`-`;return UZ(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:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.length),ask:String(D.length),warn:A,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:re,pipeShown:le,delivered:Ee,lanes:w}}function oQ(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,qU,o);let s=GU(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,KU,s)}async function sQ(e,t,n,r,i){return oQ(e,t),dQ(e,t,n,r,i)}function cQ(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(lQ(t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function lQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:tF(e.hookData)}}function uQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:lQ(s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function dQ(e,t,n,r,i){try{var a=No();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(nQ(e,t,n,i));cQ(e,t,AZ(l.view.source.effective(),Wc(t.hints.tmux)));let u=o.monotonic(),d=r-u;UZ(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await Oj(e=>Promise.all([bZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${x(e)}`),o.after),m=o.monotonic();UZ(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:rZ(f)});let{drawn:h,clickShown:g,pipeShown:_,delivered:v,lanes:y}=aQ(e,l,ox),b=t.sessionId,S=VZ(y,s.following(b)),C=nF(t.hints.client??null)===`statusline`,ee=XZ[t.encoding](C?fQ(b,h,S):h.body);return UZ(i,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{resp:ee,motion:h.body.motion,clickShown:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function fQ(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:LP(t.body,MU(HZ(e,[r,...i]),t.diagnostics,e,t.geometry))}const pQ=/^─{20,}/,mQ=/^❯(\s|$)/,hQ=/›\s*stashed$/;function gQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>pQ.test(e)?[t]:[]).at(-2);return n===void 0||!mQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function _Q(e){if(e.inMode)return{kind:`in-mode`};let t=gQ(e);return t===null?{kind:`no-prompt`}:hQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function vQ(e){return/^❯\s*\S/u.test(gQ(e)?.prompt??``)}const yQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function bQ(e){return e.screen.some(e=>yQ.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 SQ(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 CQ(e,t,n){let r=_Q(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:xQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function wQ(e,t,n,r,i){let a=await bc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function TQ(e,t){let n=await wQ(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(`
|
|
194
|
+
`);return{inMode:r!==`0`,screen:i}}function EQ(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 DQ(e,t,n){let r=await wQ(e,t,`claude-input.type`,EQ(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 OQ(e){return{read:t=>TQ(e,t),type:(t,n)=>DQ(e,t,n)}}const kQ={kind:`ok`,said:``},AQ=e=>({kind:`failed`,said:e}),jQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`};function MQ(e){let t=jQ[e.kind];return t(e)}var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},NQ=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},PQ=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function FQ(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}function IQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Dy:Oy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const LQ=Object.entries(Fx),RQ=new Set(Lx.map(e=>e.sessionKey)),zQ=()=>!1;function BQ(e,t){return NZ(e,e=>RQ.has(e)?t(e):null,zQ)}const VQ=[`preset`,`theme`];function HQ(e,t,n){let r=new Set(VQ.slice(0,n).map(e=>Fx[e].sessionKey));return NZ(e,e=>r.has(e)?t(e):null,zQ)}function UQ(e,t){let n=Array.from({length:VQ.length+1},(n,r)=>HQ(e,t,r));return e=>{let t=VQ.indexOf(e);return n[t===-1?VQ.length:t]}}function WQ(e,t,n,r){return e.flatMap(([e,i])=>{let a=IQ(t,e);return a===null||a===IQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function GQ(e,t,n){return IQ(BQ(e,t),n)}function KQ(e,t){let n=BQ(e,t);return WQ(LQ,n,UQ(e,t),t=>qQ(e,n.preset,t.configKey))}function qQ(e,t,n){return n in(hS(e.presets,t).globals??{})?jN(t,n):n}function JQ(e,t,n){let r=mS(t(Fx.preset.sessionKey),e.globals.preset,e.presets),i=MN(n);return{key:i?.scope===`globals`?qQ(e,r,i.field):n,globals:yS(e,r)}}function YQ(e,t){let{preset:n}=BQ(e,t);return QQ(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:ob(a,s);return c===void 0||ab(c)===ab(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function XQ(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return pS(e.presets).flatMap(n=>{let i=QQ(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 rb(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:ob(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const ZQ=new WeakMap;function QQ(e,t){let n=ZQ.get(e)??new Map;ZQ.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...zy(gS(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=tb(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 $Q(e,t){let n=BQ(e,t);return{from:n.preset,globals:hS(e.presets,n.preset).globals??{},picks:WQ(LQ.filter(([e])=>e!==`preset`),n,UQ(e,t),e=>e.configKey),placements:YQ(e,t)}}function e$(e,t){return NZ({...e,globals:{palette:t},presets:{}},()=>null,zQ)}function t$(e,t){let n=BQ(e,t),r=IQ(n,`theme`);if(r===null)return{kind:`rule`};let i=e$(e,r),a=yS(e,n.preset),o=Object.fromEntries(Ax.map(e=>[e,IQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Ax.some(e=>o[e]!==IQ(i,e))}}function n$(e){return{sessionKeys:Lx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...lN(e)?EX.map(t=>jN(t,e)):[],...AN(e)?Zv().map(t=>kN(t,e)):[]]}}function r$(e){return new Set(Lx.map(e=>e.configKey).filter(t=>n$(t).fileKeys.some(t=>o$(e,a$(t)))))}function i$(e,t,n){let r=KQ(e,n),i=new Set(r.map(e=>e.configKey)),a=Vx(e=>i.has(Fx[e].configKey)||t.has(Fx[e].configKey)),o=t$(e,n);return{unsaved:r.length+YQ(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function a$(e){let t=MN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return NN(t)}function o$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&o$(e[n],r)}function s$(e,t,n){let r=Hx.get(n);if(r!==void 0)return GQ(e,t,r);for(let[,t]of Zy(e))if(t.key===n)return t.default??null;return null}function c$(e,t){let n=CN(e).get(t);return n===void 0?null:String(n)}const l$={inside:()=>[],defaultOf:()=>P,menus:[]},u$=e=>`${e.key}\0${e.member}`;function d$(e){let t=new Map,n=n=>{let r=`${n.name}\0${Fy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:JJ(a,Fy(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(u$(e))??new Map;n.set(u$(t),t),o.set(u$(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(u$(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 pS(e.presets))d(gS(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(u$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(u$(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(u$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const f$=new WeakMap;function p$(e){let t=f$.get(e);if(t!==void 0)return t;let n=d$(e);return f$.set(e,n),n}function m$(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 h$(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 g$(e,t,n){let r=(r,i,a)=>{let o=m$(t(r),t=>e.get(r,t),i);(0,Y.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 _$=new Set([`1`,`true`]),v$=new Set([`0`,`false`,``]);function y$(e,t){let n=U$(e),r=n.scope===`segment-palette`?`string`:Nx(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(_$.has(t))return`true`;if(v$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function b$(e){try{return s.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function x$(e,t,n){try{if(t===null){s.rmSync(kn(e),{force:!0});return}On(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function S$(e){return/^\s*$/.test(e)?null:Ua(e)}function C$(e,t){return e!==null&&Ga(e,t)!==void 0}function w$(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(w$),...i}}return e}function T$(e){if(!$x(e))return w$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,w$(t)])),...n}}const E$=CX,D$=E$.segments,O$=E$.presets,k$=E$.root;function A$(e,t,n,r){if(!C$(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function j$(e,t){let n=NN(t);return t.scope===`segment-palette`&&A$(e,[`segments`,t.segment],D$[t.segment],n.join(`.`)),n}function M$(e){return Ua($a(e))}function N$(){return Object.entries(k$.rows).map(([e,t])=>{let n=w$(t);return{path:[`root`],fragment:M$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function P$(e,t){let n=e===null?void 0:Ga(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function F$(e,t){if(t===void 0)return null;let n=T$(t);return{path:e,fragment:M$(n),unit:{path:e,value:n}}}function I$(e,t){let n=[`presets`,t],r=[...n,`root`],i=O$[t];A$(e,n,i,r.join(`.`));let a=P$(e,r)??F$(r,i?.root);return a!==null&&xo(a.fragment)?a:null}function fne(e,t){let n=bo(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 L$(e,t){return[...N$(),P$(e,[`root`]),I$(e,t)].filter(e=>e!==null).reduce(fne,new Map)}function R$(e,t,n){for(let{node:r,...i}of L$(e,t).values())if(Co(r,n))return i;throw new Z(`${z$(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 z$(e,t){return I$(e,t)?.path??[`root`]}function B$(e,t){return t.scope===`preset-root`?z$(e,t.preset):NN(t)}function V$(e,{unit:t}){return t===null?e:mo(e,t.path,$a(t.value),Za)}function H$(e){let t=MN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function U$(e){let t=H$(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function W$(e,t,n,r,i){let a=t1(t,r),o,s=()=>(o??={chain:Y$(t,n)}).chain;n1(t,s,a),i(t,s,a),x$(t.path,r,e.logger),e.record(t.path,n,r)}function G$(e,t,n){let r=J$(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 K$=()=>{};function q$(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 J$(e,t,n){if(t===null)return[];let r=new Set($$(Q$(t),Q$(n)));return $$(Z$(e,t),Z$(e,n)).filter(e=>!r.has(e))}function Y$(e,t){try{return X$(e,t)}catch(e){if(e instanceof db)return null;throw e}}function X$(e,t){return $Y(e.locs,t===null?e.above:[nU(e.path),...e.above],TX,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:s.readFileSync(n,`utf8`))}function Z$(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Q$(e){return e.layers.at(-1)?.config??e.base}function $$(e,t,n=``){return!e1(e)||!e1(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>$$(e[r],t[r],n===``?r:`${n}.${r}`))}function e1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t1(e,t){try{return X$(e,t)}catch(e){throw e instanceof db?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function n1(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 db(e,[t]).message).join(`
|
|
195
|
+
`)}`)}function r1(e,t){let n=U$(t),r=S$(b$(e)??``),i=r===null?void 0:Ga(r,NN(n));return i!==void 0&&`value`in i?i.value:void 0}function i1(e,t,n){a1(e,t,n,[])}function a1(e,t,n,r){let i=b$(t.path),a=n.reduce((e,[t,n])=>mo(e,j$(S$(e),U$(t)),y$(t,n),Za),i??``);W$(e,t,i,q$(t,()=>o1(a,t.path,r,e=>e)),G$)}function o1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=R$(S$(s),n,i),l=Do(V$(s,c),c.path,i,a,$a(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 s1(e,t,n){let r=S$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of L$(r,t)){if(!Co(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qa(e,c):$a(s.value);if(a!==`#`)return mo(e,[...i,`rows`,a],l,Za);if(I$(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 mo(e,i,l,Za)}return e}function c1(e,t){return go(e,t,t[0]===`presets`&&t.length>2&&!DX(t[1])?2:0)}function l1(e,t,n){let r=n.map(H$),i=b$(t.path);if(i===null)return;let a=r.reduce((e,t)=>c1(e,B$(S$(e),t)),i);a!==i&&W$(e,t,i,a,K$)}function u1(e){let t=e===null?void 0:Ga(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function d1(e,t){let n=new Set([...EX,...u1(e),...t.above.flatMap(e=>Object.keys(Ia.default.parse(s.readFileSync(e.path,`utf8`)).presets??{}))].map(wM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(wM(e)))}function f1(e,t,n,r,i,a){let o=b$(t.path),s=S$(o??``),c=d1(s,t),l=[`presets`,c],u=q$(t,()=>I$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qa(o??``,u.fragment):$a(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$a(r)]]],f=i.map(([e,t])=>{let n=jN(c,e);return[j$(s,U$(n)),y$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>mo(e,t,n,Za),mo(o??``,l,`{}`,Za));return W$(e,t,o,q$(t,()=>o1(p,t.path,a.map(e=>({...e,preset:c})),s1)),G$),c}function p1(e,t,n,r){let i=b$(t.path);W$(e,t,i,mo(i??``,[`themeDefaults`,n],$a(r),Za),G$)}function m1(e,t,n){if(DX(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=b$(t.path),a=S$(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`]);W$(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>c1(e,t),i),K$)}function h1(e,t,n,r){let i=H$(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=b$(t.path),o=r.op===`remove`?r.target:r.anchor,s=q$(t,()=>R$(S$(a??``),i.preset,o)),c=V$(a??``,s),{after:l,placed:u}=g1(c,s.path,r,()=>{let e=t1(t,c).config;return pS(e.presets).map(t=>gS(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 W$(e,t,a,l,G$),u}function g1(e,t,n,r){switch(n.op){case`remove`:return{after:To(e,t,n.target),placed:null};case`insert`:{let i=tz(n.segment,n.anchor,r());return{after:Eo(e,t,i,n.anchor,n.relation),placed:i}}}}function _1(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 v1={load:()=>({}),save:()=>{},flush:()=>{}};var y1=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=v1,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Y.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,Y.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,Y.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=v1}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}};const b1={load:()=>({}),save:()=>{}},x1=new Set(Lx.map(e=>e.sessionKey)),S1=e=>x1.has(e)||e.startsWith(GN),C1=8*1024*1024,w1={past:[],future:[]},T1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var E1=class{held=Y.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,Y.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=b1){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??w1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??w1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(T1(r));i.set(T1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:_1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!S1(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:P1(i,r),o=n.get(e),s=o===void 0?a:R1(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`,I1(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(T1)),a=n.net.filter(e=>!i.has(T1(e))),o=k1(z1(L1(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(V1).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=k1(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...j1(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(T1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:z1(n,t),future:z1(i,t),...a!==void 0&&{savepoint:{at:z1([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(T1(e))),below:z1(a.below,t)}}}),new Z(`${r}: ${o.map(V1).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):b$(t.file)}write(e,t,n){t.kind===`file`?x$(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||D1(n)>C1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,O1(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${C1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function D1(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 O1({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...j1(n,1,[])}:{past:e,future:t.slice(1),...j1(n,0,[])}}function k1(e){return e.slice(-50)}const A1=e=>e===qN.member;function j1(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:M1(e.net,n),below:e.below}}}function M1(e,t){let n=new Map(e.map(e=>[T1(e),e]));for(let e of t){let t=n.get(T1(e));n.set(T1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const N1=e=>e.map(e=>({...e,before:e.after,after:e.before}));function P1(e,t){let n=[...e.past,t],r=k1(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...j1(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...F1(e.future,a),...i.below]},n.length-r.length,t)}}function F1(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function I1(e,t){return{past:e.past.slice(0,-1),future:k1([...e.future,t]),...j1(e.savepoint,0,N1(t))}}function L1(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...F1(r,t.at-i.length),...t.below]}function R1(e,t){if(A1(t.after)&&!A1(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!A1(t.after)&&A1(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function z1(e,t){return e.map(e=>e.filter(e=>!t.has(T1(e)))).filter(e=>e.length>0)}function B1(e){return e.map(V1).join(`, `)}function V1(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function H1(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 U1(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(H1))}function W1(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(H1)&&U1(t.below)}function G1(e){if(typeof e!=`object`||!e)return!1;let t=e;return U1(t.past)&&U1(t.future)&&(t.savepoint===void 0||W1(t.savepoint))}function K1(e,t){let n=e=>e.kind===`file`||S1(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 q1(e,t){return{load:()=>{let n;try{n=s.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(G1)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,K1(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{s.mkdirSync(T.dirname(e),{recursive:!0}),On(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 J1=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function Y1(e){return{...Object.fromEntries(J1.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 X1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Z1(e){let t=e=>({kind:`failed`,reason:e});if(!X1(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!X1(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!hF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${hF.join(` or `)}`)}return{kind:`ok`,value:e}}function Q1(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const $1=e=>dU(e,`doctor-marks.json`,{},Z1),e0=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},t0=(e,t)=>e.includes(t)?e:[...e,t],n0=e=>dU(e,`doctor-clicked-terminals.json`,[],e0);var r0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const i0=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},a0=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),o0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=a0(e,t);return r===void 0?n:r.projectDir},s0=(e,t)=>a0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function c0(e){let t=new Map;for(let n of e.split(`
|
|
196
|
+
`)){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*l0(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const u0={pullRequests:e=>ZX(e).showPullRequest===!0,rateLimits:e=>XX(e,`block`)||XX(e,`weekly`)};function d0(e,t){let n=new Map;for(let r of zy(gS(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=>Xy(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,qX(e,t,n.get(t))])),a=e=>r.filter(t=>u0[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const f0=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function p0(e){if(typeof e==`string`)return f0.exec(e)?.[1]}function m0(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 h0(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 g0(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=m0(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`?p0(h0(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 _0(e,t){return e===void 0?[ie(t,`.config`,`claude`),ie(t,`.claude`)].filter(e=>u(e)):[e]}async function v0(e){let t=[];for(let n of e){let e=ie(n,`projects`),r=await y0(Ro(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(ie(e,n.name))}return t}async function y0(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function b0(e,t,n){let r=[],i=[],a=ie(t,e,`subagents`);try{let t=(await Ro(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 Wo(t,void 0,void 0);if(s.kind!==`ok`){k(`Failed to check agent file ${t}`);continue}i=O0(i,t,s.value);let c=T0(Go(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 x0(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(C0(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=h0(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||S0.test(r)?`claude-code`:`prompt`}const S0=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function C0(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function w0(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=x0(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:g0(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 T0(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 E0(e){let t=T0(e);if(t.kind===`unparsed`)return k(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return w0(t.value)}catch(e){return k(`Failed to project JSONL line: ${e}`),null}}function D0(e){let t=[];for(let n of e.split(`
|
|
197
|
+
`)){let e=E0(n);e&&t.push(e)}return t}function O0(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function k0(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function A0(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Wo(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=O0(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,Go(c,e=>D0(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return I({folded:{cursor:a,value:o},longLines:i})}}
|
|
198
198
|
/*!
|
|
199
199
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
200
200
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -222,9 +222,9 @@ Config tooling:
|
|
|
222
222
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
223
223
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
224
224
|
*/
|
|
225
|
-
function
|
|
225
|
+
function j0(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function M0(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+=`
|
|
226
226
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
227
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
227
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=j0(t.toml,t.ptr),i=M0(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})}};
|
|
228
228
|
/*!
|
|
229
229
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
230
230
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -252,7 +252,7 @@ function A0(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
252
252
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
253
253
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
254
254
|
*/
|
|
255
|
-
function
|
|
255
|
+
function N0(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+=`
|
|
256
256
|
`: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)}
|
|
257
257
|
/*!
|
|
258
258
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -281,7 +281,7 @@ function M0(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
281
281
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
282
282
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
283
283
|
*/
|
|
284
|
-
let
|
|
284
|
+
let P0=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var F0=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(P0);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}};
|
|
285
285
|
/*!
|
|
286
286
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
287
287
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -309,7 +309,7 @@ let N0=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
309
309
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
310
310
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
311
311
|
*/
|
|
312
|
-
function
|
|
312
|
+
function I0(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function L0(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function R0(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?Y0(e):J0(e);return e.d++,t}return r===34||r===39?N0(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?z0(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?H0(e,r,t):e.s.charCodeAt(e.p+2)===58?U0(e,r,t):z0(e,e.p,r,0,t)}function z0(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||L0(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return B0(e,t,16,i);if(a===98)return B0(e,t,2,i);if(a===111)return B0(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else I0(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!L0(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:I0(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):V0(e,c,10,t)}function B0(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!L0(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):I0(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(`_`,``)),V0(e,o,n,t)}function V0(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 H0(e,t,n){let r=e.p++,i;if(!I0(t)||!I0(e.s.charCodeAt(e.p++))||!I0(e.s.charCodeAt(e.p++))||!I0(e.s.charCodeAt(e.p++)))return z0(e,e.p=r,t,0,n);if(e.p+=5,I0(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,!I0(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return W0(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(;I0(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return W0(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return W0(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return W0(e,e.s.slice(r,e.p),2,i,r)}function U0(e,t,n){let r=e.p;if(!I0(t)||!I0(e.s.charCodeAt(++e.p)))return z0(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;I0(e.s.charCodeAt(++e.p)););return W0(e,e.s.slice(r,e.p),4,!1,r)}function W0(e,t,n,r,i,a){if(e.ld){let a=new F0(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)}}
|
|
313
313
|
/*!
|
|
314
314
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
315
315
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -337,7 +337,7 @@ function F0(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
337
337
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
338
338
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
339
339
|
*/
|
|
340
|
-
function
|
|
340
|
+
function G0(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 K0(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;G0(e)}}
|
|
341
341
|
/*!
|
|
342
342
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
343
343
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -365,7 +365,7 @@ function W0(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
365
365
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
366
366
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
367
367
|
*/
|
|
368
|
-
function
|
|
368
|
+
function q0(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(N0(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 J0(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(K0(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=q0(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),K0(e,!0,!0);let l=R0(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),K0(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 Y0(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(K0(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(R0(e,93)),K0(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)}
|
|
369
369
|
/*!
|
|
370
370
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
371
371
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -393,7 +393,7 @@ function K0(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
393
393
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
394
394
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
395
395
|
*/
|
|
396
|
-
function
|
|
396
|
+
function X0(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 Z0(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 Q0(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++,K0(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=q0(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=X0(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(Z0(n,u,a),o=!0)}else{a=n.p;let e=X0(n,q0(n),s,c,0);!e&&!o&&Z0(n,e,a),K0(n,!0,!0);let t=R0(n,void 0);e&&!o&&(e[1][e[0]]=t)}K0(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),K0(n)}return r}``.isWellFormed;
|
|
397
397
|
/*!
|
|
398
398
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
399
399
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -421,7 +421,7 @@ function Y0(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
|
|
|
421
421
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
422
422
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
423
423
|
*/
|
|
424
|
-
const
|
|
424
|
+
const $0=e=>e.codePointAt(0).toString(16).toUpperCase(),e2=String.raw`
|
|
425
425
|
ObjC.import("AppKit");
|
|
426
426
|
ObjC.import("CoreText");
|
|
427
427
|
function lacksOf(font, points) {
|
|
@@ -468,50 +468,50 @@ function run(argv) {
|
|
|
468
468
|
: iterm(argv[1], points),
|
|
469
469
|
);
|
|
470
470
|
}
|
|
471
|
-
`;async function
|
|
472
|
-
`).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
|
|
473
|
-
`,`:family=${
|
|
474
|
-
`)){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
|
|
471
|
+
`;async function t2(e,t){let n=await e.launch({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,e2,...t],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new r0(`the font`);return{kind:`failed`,reason:`osascript failed (${Qe(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 n2=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),r2=e=>[...e].map($0).join(`,`);async function i2(e,t,n){let r=await t2(e,[`font`,t.kind,t.name,r2(n)]);if(r.kind===`failed`)return r;let{lacks:i}=r.value;return{kind:`ok`,value:{font:t.name,lacks:i===null?null:n2(i)}}}function a2(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=>!Ute(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const o2=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function s2(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=>a2(e,n));if(t!==null)return r[0];let i=r.find(e=>!o2(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 c2(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 t2(e,[`iterm`,i??``,r2(r)]);return a.kind===`failed`?a:s2(a.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:n2(e.lacks)})),i,t)}function l2(e,t){let n=e.split(`
|
|
472
|
+
`).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 u2=e=>e.replace(/[\\:,=-]/g,`\\$&`);async function d2(e,t,n){let r=await e.launch({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
473
|
+
`,`:family=${u2(t)}`],timeoutMs:3e3,category:`doctor.font`});if(!r.ok){if(r.reason===`rate-limited`)throw new r0(`the font`);return{kind:`failed`,reason:`fc-match failed (${Qe(r)})`}}return l2(r.stdout,n)}function f2(e,t,n){return process.platform===`darwin`?i2(e,t,n):d2(e,t.name,n)}function p2(e,t){let n=t||T.join(e,`.config`);return[T.join(n,`alacritty`,`alacritty.toml`),T.join(n,`alacritty.toml`),T.join(e,`.config`,`alacritty`,`alacritty.toml`),T.join(e,`.alacritty.toml`)]}function m2(e){return e===`darwin`?`Menlo`:`monospace`}const h2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function g2(e){let t=h2(e.font)?e.font:{},n=h2(t.normal)?t.normal:{},r=(h2(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 _2(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=Q0(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=g2(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(`~/`)?T.join(t,r.slice(2)):T.resolve(T.dirname(e),r);if(!s.existsSync(i))continue;let a=_2(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}async function v2(e,t,n,r){let i=p2(r,t.XDG_CONFIG_HOME).find(e=>s.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:_2(i,r,0);if(a.kind===`failed`)return a;let o=a.value?.family??m2(process.platform),c=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),l=await f2(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 y2={iterm2:c2,alacritty:(e,t,n,r,i)=>v2(e,n,r,i)};function b2(e,t,n,r,i){return y2[t.name](e,t.version,n,r,i)}function x2(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 S2=e=>dU(e,`doctor-post-mortems-read.json`,{through:null},x2);function C2(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const w2={realpath:e=>C2(()=>s.realpathSync(e)),checkoutOf:rn,digest:e=>C2(()=>en(e)),nativeShipped:xs(process.platform,process.arch)};function T2(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(T.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 E2=e=>({marks:$1(e),clicked:n0(e),postMortemsRead:S2(e)}),D2=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function O2(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 k2(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 A2=/^(sshd|mosh-server)\b/;function j2(e,t){let n=c0(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of l0(n,t))if(A2.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}async function M2(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 r0(`the processes`);return{kind:`failed`,reason:`ps failed (${Qe(n)})`}}return j2(n.stdout,t)}const N2=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function P2(e,t){let n=[];for(let r of e.split(`
|
|
474
|
+
`)){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 F2(e){let t;try{t=s.realpathSync(e)}catch{return!1}let n=N2.exec(t)?.[1];return n!==void 0&&s.existsSync(T.join(n,`bin`,`cc-candybar`))}async function I2(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:P2(t.stdout,F2)}:{kind:`failed`,reason:`ps failed (${Qe(t)})`}}async function L2(e,t){let n=await bc(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 r0(`tmux`);return n.kind===`failed`?{kind:`failed`,reason:n.reason}:k2(n.stdout)}function R2(e,t,n){return{probeTmux:t=>L2(e,t),remoteLogin:t=>M2(e,t),fontInUse:(t,r,i)=>b2(e,t,r,i,n.home),loadConfig:t,home:n.home,managedSettingsDir:n.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??os(process.platform),install:w2,daemons:()=>I2(e),forge:t=>U2(e,t),transcript:B2}}function z2(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
475
475
|
`)+1,i=n.lastIndexOf(`
|
|
476
476
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
477
|
-
`)){let t=
|
|
478
|
-
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const
|
|
479
|
-
`:null,r=
|
|
477
|
+
`)){let t=T0(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function B2(e){let t=Yo(e,gF+1);return t.kind===`ok`?I(z2(t.value.buf,t.value.fromStart)):t}function V2(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 H2={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function U2(e,t){if(Mc(t)===void 0)return{kind:`ok`,value:null};let n=Qq(await e.launch({bin:`git`,args:[...Zq],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=rJ(n.value);if(r===null)return{kind:`ok`,value:null};let i=Xq(r);if(i===null)return{kind:`ok`,value:null};let a=Gq[i],o=H2[i],s=o.loginHost(Yq(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return W2(a,s,o.nonZero,c)}function W2(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):Kq(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:Hq(r.stderr)}):{kind:`failed`,reason:Vq(e,r)}}function G2(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
478
|
+
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const K2=e=>C2(()=>cs(e));function q2(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:$o(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:K2(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 J2(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function Y2(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Kte(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:Gte(t),tmuxClient:t}}}}async function X2(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(Bte(s))return{kind:`bundling`,name:s,version:c};if(!Vte(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 Z2(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 Q2(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function $2(e,t,n,r){return{pullRequests:await Q2(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await Q2(t.rateLimits,()=>r)}}function e4(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 t4(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=NZ(d.config,r,()=>!1),p=await J2(e,t.tmux),m=Y2(p,t.terminalEnv),h=[...new Set([...jte(f),...QP(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:X2(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),$2(e,d0(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:G2(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:V2(e,o),claudeSettings:q2({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:$o(Qo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function n4(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;On(e,mo(ns(e),t.path,JSON.stringify(t.value),Qa));let r=e=>({...e,sources:K2(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||zr(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 r4={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},i4=16384;var a4=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())}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<i4){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%i4}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:r4,file:r4,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes: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:nn,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,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 o4={connectMs:200,budgetMs:500};async function s4(e,t){return c4(await l4(e),t.includes(`--json`))}function c4(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${pr(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
479
|
+
`:null,r=u4(e.value);return r===null?{stdout:n??v4(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function l4(e){return or(e,()=>({kind:`stats`}),o4,e=>`stats`in e?e.stats:void 0)}function u4(e,t=d4){let n=a4.referenceSnapshot(),r=f4(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=m4(e.version,e.sourceDigest??null),a=m4(nn,on());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 d4=Object.keys(a4.referenceSnapshot());function f4(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!p4(e))return[];if(!p4(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(...f4(e[i],t[i],a)):r.push(a)}return r}function p4(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function m4(e,t){return`${e} [${t===null?`no digest`:tn(t)}]`}function h4(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function g4(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function _4(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 v4(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${m4(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${_4(e.uptimeSec)}`),t.push(` rss ${h4(e.rssBytes)}`),t.push(` heapUsed ${h4(e.heapUsedBytes)}`),t.push(` heapTotal ${h4(e.heapTotalBytes)}`),t.push(` external ${h4(e.externalBytes)}`),t.push(` arrayBuffers ${h4(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 ${g4(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 ${g4(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 ${ol(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 ${h4(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${h4(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(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${h4(e.renderCache.accountedBytes)} / ${h4(e.renderCache.budgetBytes)}`),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(`
|
|
480
480
|
`)+`
|
|
481
|
-
`}const
|
|
482
|
-
`).join(` — `));let n=l4(t.value,[`handlerProbes`]);if(n!==null)return y4(n);let r=[];for(let e of t.value.handlerProbes){let t=k4(e);if(t===null)return y4(`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 v4({arrivals:r})}function k4(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 A4(e,t){let{host:n,clock:r}=t;return{platform:process.platform,sockets:{own:pn(n),handler:mn()},monotonic:()=>r.monotonic(),nonce:le,daemon:()=>O4(t),open:t=>{let n=E4(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>Re(r,100),opener:()=>{let t=E4(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,D4]);if(t.kind===`failed`)return t;let n=t.value.trim();return v4(n===``?null:n)},exists:s.existsSync}}function j4(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 M4(e){let t=j4(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const N4=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function P4(e){let t=j4(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function F4(e){return PQ(()=>decodeURIComponent(e))}const I4=5e3;function L4(e,t,n){if(e.reason===`rate-limited`){n(`warn`,Qe(e));return}throw e.reason===`aborted`?new MQ(t):Error(`${t} failed (${Qe(e)})`)}async function R4(e,t,n,r,i,a){let o=p(T.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:T.join(o,`stderr`),status:T.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){L4({...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=At(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;L4(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 Re(e.clock,50)}}finally{_(o,{recursive:!0,force:!0,maxRetries:3})}}function z4(e,t){B4(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function B4(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const V4=async(e,t)=>z4(F4(e),t),H4=new Set([`request`,`feed`]);function U4(e){if(!H4.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const W4=async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n),o=t.diagnosticCopy(a,U4(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);z4(o,t)},G4=async(e,t)=>B4(t,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,F4(e)],category:`click.open`},`open -a "Visual Studio Code"`),K4=async(e,t)=>{let n=P4(F4(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},q4=async(e,t)=>{let[n=``,...r]=PQ(()=>Ca(e)),i=P4(n),a=t.gates.state.gateFor(a3(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})}Z4(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})`)},J4=/^-?\d+$/;function Y4(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const X4=async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!J4.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=a3(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&&J4.test(u)?Q4(l,parseInt(u,10)):$4(`step-state`,r,l,o$(s,e=>t.sessionState.get(a,e),r)),f=Y4(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);Z4(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 Z4(e,t,n,r){let i=r.filter(e=>e.key.startsWith(WN));if(i.length===0)return;let a=YQ(a3(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function Q4(e,t){return Math.max(e.min,Math.min(e.max,t))}function $4(e,t,n,r){if(r===null)return n.min;if(!J4.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return Q4(n,parseInt(r,10))}function e3(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function t3(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:e3(a,i)}}function n3(e,t){let n=r3(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function r3(e,t){let n=e.sessionState.get(t,GU);return n===null?null:t3(n)}function i3(e,t,n){let r=r3(e,t);if(r===null)return;let{path:i}=c3(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function a3(e,t){return e.configFor(n3(e,t))}function o3(e,t){let n=r3(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function s3(e,t){let n=r3(e,t);return n===null?c$:f$(e.configFor(n))}function c3(e,t){return oU(e.locations,BU(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function l3(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const u3=async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n),o=n3(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=c3(t,o),d=qQ(s,e=>t.sessionState.get(a,e),r);r1(l3(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},d3=async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!J4.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=n3(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=c3(t,s),f=qQ(c,e=>t.sessionState.get(a,e),r),p=n1(d.path,f.key),m=typeof p==`number`?Q4(u,p):$4(`step-config`,r,u,s$(f.globals,r)),h=Y4(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);r1(l3(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})`)},f3=async(e,t)=>{let[n=``]=PQ(()=>Ca(e)),r=P4(n),i=n3(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=GQ(a,o),c=JQ(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]});m3(`save`,l,c);let d=c3(t,i);i1(l3(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(p3)].join(` `)} → ${d.path} (session=${r})`)},p3=e=>`${e.preset}/${e.id}.settings.${e.setting}=${ab(e.value)}`;function m3(e,t,n){for(let r of n){let n=t.validate(r.key,ab(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const h3=async(e,t)=>{let[n=``]=PQ(()=>Ca(e)),r=P4(n),i=n3(t,r),a=t.configFor(i),o=QQ(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]});m3(`save-preset`,s,o.placements);let l=c3(t,i),u=d1(l3(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Ix.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Px.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(p3)].join(` `)} → ${l.path} (session=${r})`)},g3=async(e,t)=>{let[n=``]=PQ(()=>Ca(e)),r=P4(n),i=n3(t,r),a=e$(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=c3(t,i);f1(l3(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(GQ(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=kx.map(e=>Px[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} ${kx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},_3=async(e,t)=>{let[n=``,r=``]=PQ(()=>Ca(e)),i=P4(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=n3(t,i),o=c3(t,a);p1(l3(t,i),o,r),t.reloadConfig(a);let s=Px.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},v3=async(e,t)=>{let[n=``,...r]=PQ(()=>Ca(e)),i=P4(n),a=n3(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=c3(t,a),l=r.map(t$),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);c1(l3(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 y3(e,t){let n=(e,t)=>[...zy(hS(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(fS(t.presets).flatMap(e=>n(t,e).map(t=>GN(CM(e),Fy(t)))));return fS(e.presets).flatMap(t=>n(e,t).map(e=>({member:GN(CM(t),Fy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function b3(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[VN]:[]])}const x3=async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n),o=n3(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=ez(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=c3(t,o),f=m1(l3(t,a),d,r,u);t.reloadConfig(o);let p=b3(y3(s,t.configFor(o)),t.sessionState.get(a,VN)).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})`)},S3=async(e,t)=>{let[n=``]=PQ(()=>Ca(e)),r=P4(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),i3(t,r,i),t.log(`info`,`undo: restored ${z1(i)} (session=${r})`)},C3=async(e,t)=>{let n=P4(F4(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(a3(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},w3=async(e,t)=>{let n=P4(F4(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);i3(t,n,r),t.log(`info`,`rewind: put back ${z1(r)||`nothing`} as edit mode found it (session=${n})`)},T3=async(e,t)=>{let[n=``]=PQ(()=>Ca(e)),r=P4(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),i3(t,r,i),t.log(`info`,`redo: re-applied ${z1(i)} (session=${r})`)},E3=async(e,t)=>{P4(F4(e)),t.effect({kind:`apply-update`})};function D3(e,t){let n=e.sessionState.get(t,KU);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 Bn(r)}function O3(e,t,n){let r=YF(n);e.sessionState.setBatch(t,fI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${$F(n.config)} ${uI(n.nerdFont,n.marks)} ${eI(n.terminal,n.clicked)} ${tI(n.terminal,n.width)} ${nI(n.install)} ${iI(n.daemon)} ${aI(n.data)} ${lI(n.transcripts)} ${oI(n.frames,n.claudeSettings)} ${cI(n.claudeSettings.origin.sources)} (session=${t})`)}async function k3(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 e4({...n,loadConfig:()=>r},D3(e,t),n3(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:o0(i,a)},$2(t,a),E2(e.doctorStores))}catch(e){throw e instanceof n0?new Z(e.message):e}let s={facts:o,install:w2(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(n3(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:k3(e,t,n,i)}};return s}const A3=(e,t)=>{let n=D2(e.doctor);return k3(e,t,n,n.loadConfig(n3(e,t)))};async function j3(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=E2(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:X2(e.arrival),install:i,clicked:M3(e,o)}}function M3(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?uF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>e0(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 N3={gathers:!0,prepare:async(e,t)=>{let n=P4(F4(e)),r=await A3(t,n);return async e=>O3(e,n,await j3(e,n,r))}},P3=async(e,t)=>{let n=S4(F4(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}`)},F3={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=PQ(()=>Ca(e)),i=P4(n),a=XF(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await A3(t,i);return async e=>{let t=await j3(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=t4(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} → ${$te(n.fix)} (session=${i})`),O3(e,i,r.value)}}},I3={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=PQ(()=>Ca(e)),a=P4(n),o=XF(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!mF.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${mF.join(` or `)}`);let s=await A3(t,a);return async e=>{let t=await j3(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=>Z1(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})`),O3(e,a,{...t,marks:c})}}},L3=async(e,t)=>{let[n=``,r=``]=PQ(()=>Ca(e)),i=P4(n),a=Object.values(t.configFor(n3(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=xQ(D3(t,i).tmux);if(s.kind===`refused`)throw new Z(`${r} was not typed: ${s.reason}`);t.effect({kind:`type-slash`,pane:s.hint,line:o.slash})};function R3([e=``,t=``,n=``,r=``],i){let a=P4(e),o=n3(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=OS(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:{...J1({sessionId:a,projectDir:o.projectDir,claudeConfigDir:D3(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const z3=new Map([[Ki,N4(V4)],[qi,N4(G4)],[Wi,N4(q4)],[Gi,N4(X4)],[Yi,N4(u3)],[Xi,N4(d3)],[ta,N4(v3)],[Zi,N4(f3)],[Qi,N4(h3)],[$i,N4(g3)],[ea,N4(_3)],[na,N4(x3)],[ra,N4(S3)],[ia,N4(T3)],[aa,N4(C3)],[oa,N4(w3)],[Ji,N4(K4)],[sa,N4(E3)],[ca,N3],[la,F3],[ua,I3],[da,N4(P3)],[fa,N4(L3)],[`run`,N4(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=PQ(()=>Ca(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=R3(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[pa,N4(async(e,t)=>{let[n=``,r=``,i=``,a=``]=PQ(()=>Ca(e)),o=P4(n),s=i;if(!t.links.verify(HU(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=VU(BU(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(n3(t,o))})],[ma,N4(W4)]]),B3=new Set([Wi,Gi,Yi,Xi,ta,Zi,Qi,$i,ea,na,ra,ia,aa,oa,Ji,sa,ca,la,ua,fa,`run`,pa,ma]);function V3(e,t){return H3(e===`dispatch`?Ea(t):[{verb:e,value:t}])}function H3(e){let t=e.find(e=>B3.has(e.verb)),n=t===void 0?``:PQ(()=>wa(t.value));return n===``?null:j4(n)}const U3=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function W3(e,t,n,r){let i=r??await n.gather(n=>e.prepare(t,n)),a=[];await i({...n,effect:e=>void a.push(e)});for(let e of a)n.effect(e)}async function G3(e,t){let[n]=Oa(Ea(e)),r=n===void 0?void 0:z3.get(n.verb);return r?.gathers?U3(r,n.value,t):void 0}async function K3(e,t,n){let r=[],i=!1,a=Ea(e),o=H3(a);for(let[e,{verb:o,value:s}]of Oa(a).entries()){let a=z3.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await W3(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof MQ)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&&Sc(t.sessionState,o.id,r.join(`
|
|
483
|
-
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function q3(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function J3(e,t,n,r){let i=e===null?null:o3(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)}q3(e)}),c=[],l=e=>h$(e,e=>s3(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d=[];try{await r({...u,effect:e=>void d.push(e),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)}f&&t.described(d),q3(c)}function Y3(e,t,n){return async(r,i)=>{let a=V3(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,i.asker,()=>t(r,i),(e,t)=>J3(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const X3=new Map([...[...z3].map(([e,t])=>[e,Y3(e,async(e,n)=>t.gathers?U3(t,e,n):void 0,(e,n,r)=>W3(t,e,n,r))]),[Ui,Y3(Ui,G3,K3)],[da,P3]]);Object.freeze([...X3.keys()]);function Z3(e){let t=X3.get(e);return t===void 0?null:{name:e,run:t}}function Q3(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>J3(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=m$(s3(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:P}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}const $3=[],e6={request:async({req:e,at:t,waitEndsAt:n,facts:r},i)=>({answer:await oQ(i,e,t,n,r),effects:$3,facts:[]}),click:async({verb:e,value:t,arrival:n,pending:r,asker:i},{verbCtx:a,menuIdle:o})=>{r!==null&&o.clickArrived(r);let s=[],c=null;try{await e.run(t,{...a,arrival:n,asker:i,described:e=>void s.push(...e)})}catch(e){c={error:e}}finally{r!==null&&o.clickSettled(r)}return{answer:c,effects:s,facts:[]}},"menu-idle":async({session:e,idle:t},{verbCtx:n})=>{let r=[];return await Q3(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":async({of:e,outcome:t},{verbCtx:n})=>{let r=[];return await n.journalTurns.take(`effect-done`,{waited:e=>r.push([`turnWait`,`${e}ms`]),gone:()=>!1},async()=>{t.kind===`failed`&&e.session!==null&&Sc(n.sessionState,e.session,t.said,n.now())}),{answer:void 0,effects:$3,facts:r}}};async function t6(e,t){let n=e6[e.kind],r=await n(e,t),i=c6(e),a=o6[e.kind],o=a(e,r);return o!==null&&t.log(o.level,KZ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>jQ(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?n6:f6(t,i,r.effects)}}const n6=Promise.resolve(),r6={level:`info`,facts:[[`outcome`,`ok`]]},i6=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),a6={ok:`info`,failed:`warn`},o6={request:()=>null,click:(e,{answer:t})=>t===null?r6:i6(t),"menu-idle":()=>r6,"effect-done":({effect:e,outcome:t})=>({level:a6[t.kind],facts:[[`effect`,jQ(e)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},s6={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({verb:e,pending:t})=>({verb:e.name,session:t}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e};function c6(e){let t=s6[e.kind];return t(e)}const l6={launch:({spec:e,what:t},{verbCtx:n})=>u6(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await SQ(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:kQ(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),OQ)};async function u6(e,t,n){let r=await e.launch({...t,timeoutMs:I4});return r.ok?OQ:kQ(`${n} failed (${Qe(r)})`)}async function d6(e,t){let n=l6[e.kind];try{return await n(e,t)}catch(e){return kQ(e instanceof Error?e.message:String(e))}}function f6(e,t,n){return e.verbCtx.journalTurns.performing(t.session,async()=>{for(let r of n){let n=await d6(r,e);try{await t6({kind:`effect-done`,of:t,effect:r,outcome:n},e)}catch(t){e.log(t instanceof MQ?`info`:`error`,`apply: effect-done not applied (${jQ(r)} ${n.kind}: ${n.said}): ${x(t)}`)}}})}const p6=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`]),m6=[[`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`]],h6=[[`workspace.added_dirs`,`string-list`]];function g6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of m6){let i=y6(n,e);if(i==null)t.missingRequired.push(e);else{let n=_6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of h6){let i=y6(n,e),a=i===void 0?r:v6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))p6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function _6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function v6(e){return Array.isArray(e)&&e.every(e=>_6(e)===`string`)?`string-list`:_6(e)}function y6(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 b6(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:gP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function x6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Rn.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Rn.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function S6(e,t,n,r){let{report:i}=g6(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=j4(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!D(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=x6(e.encoding);s.ok||a.push(s.problem);let c=mr(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=Bn(e),{configFile:u,refusedArgs:d}=b6(e.args,e.cwd,r);return{ok:!0,req:{...e,deadline:c,encoding:s.encoding,sessionId:o.id,hints:l,rateLimits:Rte(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:yP(u,l.configEnv)},refusedArgs:d}}}function C6(e,t){switch(e){case`vars`:return{what:e,vars:w6(t)};case`segments`:return{what:e,segments:k6(t)};case`config`:return{what:e,config:N6(t)}}}function w6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=D6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=T6(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:E6(r.lastUpdatedMs(),t.clock)})}return o}function T6(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 E6(e,t){return e===null?null:Math.max(0,t.now()-e)}function D6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,O6(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}`,O6(i));return t}function O6(e){return e.kind}function k6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=j6(n),o=A6(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:M6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function A6(e){let t=new Map;for(let n of fS(e.presets))for(let r of zy(hS(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Fy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function j6(e){let t=[],n=new Set;for(let r of zy(eS(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 M6(e,t,n){let r=new Set([...$S(e,t).keys()].flatMap(e=>_C(e,n)));return Array.from(r).sort()}function N6(e){return e===null?null:e.config}const P6=[`vars`,`segments`,`config`];function F6(e){return typeof e==`string`&&P6.includes(e)}const I6=e=>({resp:e,exitAfterFlush:null,delivered:qZ}),L6=e=>({kind:`reply`,...e}),R6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},z6=(e,t)=>L6(I6({ok:!1,error:t,code:e,daemonV:3}));function B6(e){let t=j4(e.sessionId);if(!t.ok)return z6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return z6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${ix.join(`, `)}): it predates the lane toggles — update it`);let n=fx(e.lane);return n===null?z6(`BAD_REQUEST`,`subscribe needs a lane, one of ${ix.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function V6(e,t,n,r,i){if(t.kind===`url`)return L6(I6(await Y6(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?z6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?B6(a):typeof a.kind!=`string`||!Object.hasOwn(R6,a.kind)?z6(`BAD_REQUEST`,`unknown kind`):L6(await H6(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,delivered:qZ})}async function H6(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:ee,sourceDigest:w,doctorStores:te}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:qZ};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return I6(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 I6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:U6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:Vo(),renderCache:c.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(He(new Date(o.now()))),bundle:ee,sourceDigest:w,daemon:b.serving(),doctorStores:E2(te)})});if(t.kind===`render`){let c=new Date(o.now()),l=He(c),u=o.monotonic(),d=Ie(r,u),f=[],p=++a.requestsTotal,m=S6(t,a,e.log,e.home),h=(t,n)=>C.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Qo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:zte(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await t6({kind:`request`,req:m.req,at:l,waitEndsAt:Fe(u,hr(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({answer:{resp:t,motion:n,clickShown:r,pipeShown:i,delivered:a}})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r!==null&&Cc(_,m.req.sessionId,r),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:JZ(e),delivered:qZ})):t8(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,HZ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=GZ(`render`,f,g.outcome,A(o,u));return e.log(v,y),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return I6(await q6(e,r,n,i,(n,r)=>J6(e,t,n,r)));if(t.kind===`debug`){if(!F6(t.what))return I6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${P6.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`?K6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??jx(`colorCompatibility`)):G6};return I6({ok:!0,debug:C6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function U6(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 W6={endcaps:jx(`endcaps`),colorCompatibility:jx(`colorCompatibility`),wrap:jx(`autoWrap`),padding:jx(`padding`),width:1/0},G6=new Map;function K6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Pte(i,{...W6,colorCompatibility:t}));return n}async function q6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Ie(t,o)}ms`]],c=await i(s,()=>n()||r());HZ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=GZ(`click`,s,c,A(a,o));return e.log(l,u),$6(c)}async function J6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};HZ(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}`]}:X6(()=>Q6(e,a,o,i,n,r))}async function Y6(e,t,n,r,i){return q6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(HZ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Zn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Zn].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 X6(()=>Q6(e,o.verb,o.value,s,n,r))})}async function X6(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof MQ?{kind:`closing`,error:e}:e instanceof NQ?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const Z6={link:`verb`,"tmux-status":`linkVerb`};async function Q6(e,t,n,r,i,a){if(t===`tmux-status-click`)return HZ(i,{verb:t}),e8(e,n,i,a);let o=Z3(t);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};HZ(i,{[Z6[r.via]]:t});let s=V3(t,n),c=s?.ok?s.id:null;s===null?HZ(i,{sid:`-`}):c!==null&&HZ(i,{sid:c});let{answer:l}=await t6({kind:`click`,verb:o,value:n,arrival:r,pending:c,asker:{placed:e=>HZ(i,{placeWait:`${e}ms`}),gathered:e=>HZ(i,{gather:`${e}ms`}),waited:e=>HZ(i,{turnWait:`${e}ms`}),gone:a}},e);if(l!==null)throw l.error;return{kind:`ok`}}function $6(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 JZ(e.error)}}async function e8(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(HZ(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`):Q6(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await R4(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,I4,e.tmp),{kind:`ok`}}const t8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:qZ});function n8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return T.join(e,`update-act`,n)}const r8={kind:`idle`};function i8(e){if(e===null)return r8;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 a8=e=>({stdout:T.join(e,`stdout`),stderr:T.join(e,`stderr`),status:T.join(e,`status`)}),o8=e=>T.join(e,`record.json`);function s8(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 c8(e){let t=Yo(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 l8(e,t){let n=T.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(T.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const u8=e=>e.now()-o.uptime()*1e3;async function d8(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 f8(e){try{return JSON.parse(s.readFileSync(o8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const p8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function m8(e,t,n,r){let i=null;async function a(a){let o=T.join(e,String(a)),c=f8(o);if(c===null)return null;if((i===null||!p8(i.record,c))&&(i={record:c,ours:await d8(c,t,n,u8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=a8(o),u=At(l.status),d=u===null?null:c8(l.stderr)??c8(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=s8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${T.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function h8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(T.join(e,`.claim-`));try{return s.writeFileSync(o8(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 g8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=T.join(t,String(c)),u=e.launchJobSync(i,a8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!h8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return _8;if(s8(t).some(e=>e>c))return l8(t,c),_8;d=!0}finally{d?u.release():u.withdraw()}for(let e of s8(t).filter(e=>e<c))l8(t,e);return{ok:!0,act:c}}const _8={ok:!1,reason:`another act claimed this bundle first`};function v8(e,t,n){let r=a8(T.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function y8(e,t,n){if(t.kind===`pending`)return Ao(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,Y.compareStructural)(r,t))return e}return{...t,at:n}}var b8=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 x8(e){return e.kind===`source`?e.newer.digest:ms(e.newer)}const S8=e=>`${e.version} [${tn(e.digest)}]`;function C8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:S8(e.newer),running:S8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:ms(e.newer),running:ms(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${gs}@${ms(e.newer)}`,`install`]}}}}function w8(e,t,n){if(e===null)return[];let r=x8(e);if(!n.enabled||n.dismissed===r)return[];let i=C8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
484
|
-
`),c=t.kind===`running`?gU(`[${i.busy}]`,null):gU(`[${i.act}]`,Ta([{verb:sa,args:[n.sessionId]}])),l=[gU(a,null),c,gU(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,jz,r]}])),gU(`[disable]`,Ta([{verb:Yi,args:[n.sessionId,Mz,`false`]},{verb:Wi,args:[n.sessionId,Nz,`false`]}]))],u=o.map(e=>[gU(e,null)]);return[{severity:pU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function T8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return I({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return L;case`unchecked`:return R(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return E8(t)}}function E8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return I({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return L;case`unchecked`:return R(`release: unchecked: ${t.reason}`,`read`)}}function D8(e){switch(e.kind){case`current`:return[`info`,`build: current ${S8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${S8(e.source)}, running ${S8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function O8(e){switch(e.kind){case`current`:return[`info`,`release: current ${ms(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${ms(e.latest)}, running ${ms(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${ms(e.installed)}, latest ${ms(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function k8(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=Ao(`unread`),g=Ao(`unread`),_=async e=>{let t=await i.startTime(e);if(w)throw new MQ(`apply-update`);return t},v=m8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new b8,ee=e=>C.run(`acts`,e),w=!1,te=[],ne=(e,t)=>{te.push(n.every(t,e,{unref:!0}))},T=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function re(){let e=T(),t=e===null?null:x8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(jz,[t])})}function E(){let e=w?L:T8(h,g),r=y8(t.get(),e,We(n));(0,Y.runInAction)(()=>t.set(r)),re()}function D(){let e=cn(a,()=>an(o));return h=I(e),x(D8(e)),E(),e}async function ie(){let e=vs(nn,await _s(gs,d,u,n));g=I(e),S(O8(e)),E()}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 MQ?{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}=v8(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 w||se(e),e});if(w||!e.ok)return;let t=i8(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`),D(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await ee(ce),!w&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=D();ne(D,c),te.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),ne(()=>void ie(),l))},close(){w=!0,E(),te.forEach(e=>e())},notice:e=>w8(T(),y??r8,e),running:()=>ee(async()=>{let e=await oe(()=>v.read());return e.ok&&i8(e.value).kind===`running`}),error:()=>O,act:()=>ee(async()=>{if(w)throw new MQ(`apply-update`);let e=await oe(()=>v.read());if(w)throw new MQ(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=T();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=C8(t),a=e.value;if(i8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await g8(r,s,a===null?null:a.act,x8(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 A8(){return Y.observable.box(Ao(`unread`),{deep:!1})}function j8(e,t){try{return I(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?L:R(e.message,`read`)}}function M8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function N8(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:j8(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=j8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!M8(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 P8=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 F8=`pass`,I8={okMs:5*6e4,failedMs:45e3},L8=I8.okMs;function R8({failures:e}){return _j(I8,e,L8)}function z8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function B8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function V8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function H8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:T.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Yc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${Xc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function U8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function W8(e){e.missed=!0,Sj(e,`unread`)}function G8(e,t){return e.missed&&e.reading.get().kind===`pending`&&xj(e,t.size>0?R([...t].join(`; `),`read`):L),`unkeyed`}function K8(e,t){let n=Tj(e);return t===null||n.kind!==`ok`?n:I({...n.value,pullRequest:Tj(t)})}const q8=R(`git cache closed`,`read`);function J8(e){return t=>R(`${e} threw: ${String(t)}`,`read`)}var Y8=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 Mo(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new Fj(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 hj({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=R(`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={},r){let i=this.asked(e,t,n,r);if(i.kind===`settled`)return Oj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>K8(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:q8};let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`settled`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.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))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new P8,watch:this.followWatch(e,null).watch,period:new vj(()=>{n.refresh.share(F8,()=>this.refreshPass(n))},this.clock),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=H8(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(F8,()=>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,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&W8(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(F8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:yj(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=V8(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(B8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}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=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(J8(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,xj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of Rq(n.value))c.add(e)});let l=U8(o),u=a===null||i.length===0?`-`:l===void 0?G8(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,z8(n),c.size===0?I(null):R([...c].join(`; `),`read`),A(this.clock,t))}prSource(e){let t={period:new vj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:L,reading:yj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(J8(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(W8(t),`owed`):(Sj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,xj(t,a.outcome),t.period.landed(R8(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(J8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:L)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(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||(xj(t,i),t.period.landed(R8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=R(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())Cj(n,t);e.pr!==null&&Cj(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()}},X8=class{static usageDir(e){return T.join(e,`usage`)}static locksDir(e){return T.join(e,`locks`)}static isLocked(e,t){let n=T.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=T.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 Re(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=T.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=T.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 Re(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 Re(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=T.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 Z8={"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 Q8=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 X8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await X8.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(Z8).length} models`),this.executionCache=Z8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(Z8).length} models`),Z8)}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`}},$8=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 e5(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 t5={okMs:60*1e3,failedMs:10*1e3},n5={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function r5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function i5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const a5={entries:0,cost:0,breakdown:i5(),days:new Map};async function o5(e,t,n,r){let i=kX(new Date(r5(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 Q8.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=kX(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...DX};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 s5(e){let t=0,n=0,r=i5(),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)??{...DX};OX(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:n5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function c5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function l5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!c5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...DX};OX(r,t),n.set(e,r)}return Object.fromEntries(n)}async function u5(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 d5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function f5(e,t){(0,Y.runInAction)(()=>e.set(t))}var p5=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new $8;scans;daySets=new Map;speedFlight=new $8;requestFlight=new $8;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 Fj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new Aj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??t5,watch:kj,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()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Po(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:I(d5(t.kind===`ok`?t.value.sessionInfo:n5,e))},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Ao(`unread`);let r=n.failure.get();return r===null?I(d5(n.record?.sessionInfo??n5,t)):R(r,`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=${z(e)}`,`request`,a,A(this.clock,i)),f5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e){return this.request(e?.session_id??``,e?.transcript_path).today()}declareToday(e,t){if(this.closed)return Oj(R(`usage store closed`,`read`));let n=g0(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?I({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return L;let r=n.failure.get();if(r!==null)return R(r,`read`);let i=n.record;return i===void 0||c5(i.transcriptPath,t)?L:I(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return L;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return f5(this.hold(e).speed,t),t;let r=e5(t.kind===`ok`?t.value.sessionInfo.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=I({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return f5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Ao(`unread`):L}async ingest(e,t,n,r){if(!e)return L;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,I(i);if(!t)return i?I(i):L;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 R(`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,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),I(c)):l===void 0?I(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,Y.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:Y.observable.box(null),speed:Y.observable.box(void 0,{deep:!1})};return(0,Y.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 NC(`today over ${e.join(`,`)}`,()=>l5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await y0(e,E(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of O0(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 k0(e,r,a5,(e,t)=>o5(e,t,dn(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 O0(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return I({files:i,...s5(i),mainStamp:a})}async scan(e){try{let t=r5(this.clock.now()),n=await _0(e),r=[];for(let e of n){let n=await v0(Ro(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await v0(zo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Fo(a)})}}let i=[],a={hits:0,misses:0};return await u5(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=${z(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?R(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):I({sessions:r.length,read:a.misses})}catch(e){return R(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=kX(new Date(e)),n=0,r=0,i=0;return(0,Y.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,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},m5=class{values=Y.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,Y.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)}})}},h5=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 m5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Po(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 k0(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(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 O0(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Ao(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function g5(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 _5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new h5(void 0,g5,(e.ledger??new Fj(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return k(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);k(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?I(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,v5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return I(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,v5(e))}contextFrom(e,t){if(e.kind===`failed`)return R(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),L):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),I({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function v5(e){return e.context_window?.context_window_size??2e5}const y5={messageCount:0,nonPrompts:0,recent:[]},b5=new Set([`turn`,`interrupt`,`claude-code`]);function x5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!b5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function S5(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 C5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new h5(y5,x5,(e.ledger??new Fj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?w5(e,n,await this.fold.read(e,t.transcript_path)):L}metricsOf(e,t){let n=t.cost;if(!n)return L;let r=this.fold.answer(e);return r.kind===`pending`?r:w5(e,n,r)}};function w5(e,t,n){return n.kind===`failed`?R(`metrics (${e}): ${n.reason}`,n.failedAt):I({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:S5(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const T5={command:null,todos:[],pending:[],done:[]};function E5(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 D5(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 O5(e,t){if(t.isSidechain)return e;let n=D5(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=E5(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 k5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>E5(e,t.name),[]),done:e.done}}var A5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new h5(T5,O5,(e.ledger??new Fj(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return j5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:j5(e,t)}};function j5(e,t){return t.kind===`failed`?R(`activity (${e}): ${t.reason}`,t.failedAt):I(k5(t.value))}const M5=3e4;var N5=class{names;constructor(e){let t=e.logger??Pe;this.names=new Aj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>P5(e.launcher,t),every:()=>({okMs:M5,failedMs:M5}),watch:kj,maxEntries:64,logger:t,ledger:e.ledger??new Fj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function P5(e,t){let n=await bc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return R(n.reason,`read`);let r=n.stdout.trim();return r?I(r):L}const F5=6e4,I5={okMs:F5,failedMs:F5};function L5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function R5(e,t){try{let e=t();return Promise.resolve(e===``?L:I(e))}catch(t){return Promise.resolve(R(`host.${e}: ${String(t)}`,`read`))}}var z5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>I5,watch:kj,maxEntries:1,logger:t,ledger:e.ledger??new Fj(t),clock:e.clock};this.name=new Aj({...n,name:`host.name`,read:()=>R5(`name`,()=>L5(o.hostname()))}),this.user=new Aj({...n,name:`host.user`,read:()=>R5(`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()}},B5=class{known=new m5(64);refreshes;constructor(e,t=Pe,n=new Fj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=V5(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=AI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Ao(`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 V5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Fo(t)}catch(e){return`unread:${e.code??`error`}`}}const H5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function pne(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 mne=class{known=new m5(256);refreshes;constructor(e,t=Pe,n=new Fj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Po(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??Ao(`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 hne(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,A(this.clock,r)),i}};async function hne(e){let t=await gne(e);return t.kind===`ok`?I(Math.floor((t.value+36e5)/1e3)):t}async function gne(e){for(let t of[65536,1048576]){let n=await Jo(e,t);if(n.kind!==`ok`)return n;let r=_ne(n.value.buf,n.value.fromStart);if(r!=null)return I(r);if(n.value.fromStart)return L}return L}function _ne(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!H5.test(t))continue;let r=pne(t);if(r!=null)return r}return null}const U5=e=>aH(e),W5=e=>T.join(e.storage.folder,U5(e.sessionId)),G5=e=>JSON.stringify([e.folder,e.generation]),K5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var vne=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??Kc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new Aj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(W5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:kj,maxEntries:256,logger:e.logger,ledger:e.ledger??new Fj(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`||!qc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${z(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(G5(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:${G5(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(G5(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=G5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>K5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(T.join(n.folder,T.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(W5(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`&&qc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${z(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>K5(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=${z(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>K5(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(G5(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=il(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 R(t,`read`);let n=W5(e),r;try{r=await s.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?L:R(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return L;let i=Uj(r);return i.kind===`failed`?R(`${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=${z(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=T.join(e.folder,a.name);try{let{mtimeMs:r}=await s.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&U5(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 yne(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new z5({clock:n,logger:r,ledger:i}),gitProvider:new Y8({inner:new fJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new p5({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new _5({clock:n,logger:r,ledger:i}),metricsProvider:new C5({clock:n,logger:r,ledger:i}),activityProvider:new A5({clock:n,logger:r,ledger:i}),tmuxService:new N5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new B5(n,r,i),cacheExpiry:new mne(n,r,i),managedStorage:new vne({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new PX,log:e.logger,clock:n}}function*q5(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*bne(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 fS(e.presets)){for(let n of zy(hS(e,t).node))n.when!==void 0&&(yield n.when);let n=vS(e,t);for(let e of ny){let t=n[e];ry(t)&&(yield t)}}for(let[,t]of q5(e))for(let[,e]of Jy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of kS(t))yield e}function xne(e,t,n){let r=HG(t),i=new Set,a=new Set,o=new Set;for(let e of bne(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of rC(e,t.helpers))a.add(n);for(let n of dC(e,t.helpers))o.add(n)}for(let[,e]of q5(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 fS(t.presets))for(let n of zy(hS(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(q5(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 Sne(e){return Math.floor(Math.max(e/4,e*Vr-67108864))}const Cne={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function J5(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[iH(NS(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[NS(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>PS(e)(t)&&t!==iH(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${xP(e,`<default>`)}: projections=${[...rq(n).keys()].join(`,`)||`-`} instantSegments=${xq(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 wne=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Tne=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${wne(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Ene(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.projectDir)} cwd=${z(e.cwd)} cause=${z(Tne(t))} state=${n} files=${z(xP(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 Dne(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function One(e,t,n){return e+`\0`+t+`\0`+(n??``)}function kne(e,t){return new Set(fS(e.presets).filter(n=>hS(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Ane(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,T.join(e.projectDir,RH)])];return cj({named:[...QH(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 jne(e){return e.filter(Boolean).join(`
|
|
486
|
-
`)||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 Mne(e){let{loaded:t,chain:n}=e;return Rj({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 Nne(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=QY(t.locs,t.layers,wX,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Nne(i.config,n)};return{kind:`resolved`,...a,key:Mne(a),warnings:r}}catch(e){return e instanceof db&&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??wX,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new UC(t.clock),m=new dM(t.runs,p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=hq(o,m,n,t.compile??mq(t.signer),Fne),f.push(...h.loadWarnings);let r=m.view();f.push(...vq(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 db&&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,neededInputPaths:JX(o),authoredRoots:kne(l,u),fileHeldSettings:n$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>xne(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=>jne([...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 Pne(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=nU(r.locations,BU(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 Pne({repos:s,advisories:[lU(r.locations,e,t),sU(o),YH(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 Fne=new Set([`directory`]),n7=new Set([`view`]);function Ine(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new ij;vq(e.config,l,t,n7);let d=()=>jZ(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),aZ(R(`view declaration threw: ${String(t)}`,`read`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=Y.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,Y.runInAction)(()=>m.set(r))},g=(0,Y.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=[],v=()=>{g();for(let e of _)e();return u.close(),l.dispose()},y;try{y=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get(),onDispose:e=>_.push(e)})}catch(e){throw v(),e}NK(e.compiled,l.variableStore,l,y);let b=(0,Y.reaction)(()=>[y.payload(),y.selections(),l.published(),e.registry.published()],()=>o(c),{equals:Y.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:y,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:b,dispose:()=>(b(),v())}}var Lne=class{entries=new Map;answersWatch;stopSweep=null;closed=!1;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(RU(e.stateDir),{recursive:!0});let{dir:n,name:r}=aj(zU(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)??bq(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=One(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`,J5(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=${Ir(this.accountedBytes())}/${Ir(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++,this.armSweep();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 o.read=!0,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}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{sessionId:i}=n,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=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=Ine(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}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}`))}armSweep(){this.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.releaseIdle(),{unref:!0}))}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.stopSweep!==null&&(this.stopSweep(),this.stopSweep=null)}close(){if(this.closed)return;this.closed=!0,this.stopSweep?.(),this.stopSweep=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.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,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=${Ir(this.accountedBytes())}/${Ir(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(),this.leaseOf(r).read,`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`,Dne(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){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`,J5(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.reloadInto(t,e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=Ane(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 Rne=e=>!x1(e)&&!vI(e)&&e!==`update.dismissed`&&e!==Bi;var zne=class{past=Y.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:g1(e,Rne,(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,Y.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,Y.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)})}};const r7=(e,t)=>e?t:Ao(`unread`),i7=(e,t)=>e.kind===`ok`?I(t(e.value)):e;function Bne(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return L;case`ok`:return e.value.pullRequest??Ao(`unread`)}}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 Vne({pullRequest:e,...t}){return t}function o7(e,t,n,r,i){let{lanes:a,gathered:o}=n,s=r7(o.git,a.git),c=(e,t)=>y8(e,t,i),l=e?.builtins,u={session:c(l?.session,r7(o.session,a.usage)),today:c(l?.today,r7(o.today,n.today)),speed:c(l?.speed,r7(o.speed,a.speed)),context:c(l?.context,r7(o.context,a.context)),metrics:c(l?.metrics,r7(o.metrics,a.metrics)),activity:c(l?.activity,r7(o.activity,a.activity)),cache:c(l?.cache,r7(o.cache,a.cache)),autocompact:c(l?.autocompact,r7(o.autocompact,a.autoCompact)),git:c(l?.git,i7(s,Vne)),pr:c(l?.pr,Bne(s)),tmux:c(l?.tmux,i7(r7(o.tmux,a.tmuxSession),e=>({session:e}))),hostName:c(l?.hostName,r7(o.hostName,a.hostName)),hostUser:c(l?.hostUser,r7(o.hostUser,a.hostUser))},d=Object.fromEntries(n.declaredSources.map(t=>[t,c(e?.sources[t],a.sources.get(t)??Ao(`unread`))])),f={builtins:u,sources:d,update:r,diagnostics:n.faults};return e!==void 0&&a7(u,e.builtins)&&a7(d,e.sources)&&(0,Y.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:1,session:t,seq:e===void 0?1:e.seq+1,...f}}const s7=(e,t)=>e.failure===t?e:{...e,failure:t};function Hne(e,t,n,r){if(t.kind===`failed`)return s7(e,t.reason);try{let i=o7(e.document,r,t.readings,t.update,n);return e.failure===null&&i===e.document&&t.compose===e.compose&&t.draw===e.draw?e:{document:i,compose:t.compose,draw:t.draw,failure:null}}catch(t){return s7(e,`stamping the facts document: ${String(t)}`)}}function Une(e){return({sessionId:t,state:n,store:r,declared:i,onDispose:a})=>{let o=n=>e.sessionState.get(t,n),s=r.derive(`session.effective`,`computed`,()=>MZ(n.config,o,e=>n.authoredRoots.has(e))),c=r.derive(`session.inputs`,`computed`,()=>{let{facts:t,lanes:r,preset:a}=i();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,neededInputPaths:n.neededInputPaths(a),deps:{...e.providers,lanes:()=>r}}}),l=r.derive(`session.readings`,`computed`,()=>cZ(c.read(),n.sources)),u=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n,neededInputPaths:r}=c.read();return{hookData:t,hints:n,neededInputPaths:r,home:e.providers.home}}),d=r.derive(`session.draw`,`computed`,()=>({effective:s.read(),configFacts:{...r$(n.config,n.fileHeldSettings,o),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),f=e.providers.clock,p=Y.observable.box({document:o7(void 0,t,l.read(),e.update(),We(f)),compose:u.read(),draw:d.read(),failure:null},{deep:!1});a((0,Y.reaction)(()=>{try{return{kind:`read`,readings:l.read(),update:e.update(),compose:u.read(),draw:d.read()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},n=>(0,Y.runInAction)(()=>{let r=p.get(),i=Hne(r,n,We(f),t);i.failure!==null&&i!==r&&e.providers.log(`error`,`session facts sid=${JSON.stringify(t)}: ${i.failure}`),p.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let m=r.derive(`session.payload`,`computed`,()=>{let{document:e,compose:t,draw:n}=p.get();return pZ(e,t,n)});return{payload:()=>m.read(),effective:()=>p.get().draw.effective,facts:()=>p.get().document,hints:()=>p.get().compose.hints,failure:()=>p.get().failure,selections:()=>p.get().draw.effective}}}const c7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,l7=`#{session_id} #{client_control_mode} #{pane_id}`;function u7(e){let t=new Set;for(let n of e.split(`
|
|
481
|
+
`}const y4=e=>({kind:`ok`,value:e}),b4=e=>({kind:`failed`,reason:e});var x4=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const S4=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function C4(e){return S4.test(e)?e:null}function w4(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return y4(null);let n=t.value;return y4({app:n,forwarder:e.exists(js(n))})}async function T4(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 E4(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}://${da}/${n}`);return(r===null?await T4(e,n):null)??{kind:`lost`,unopened:r,opener:w4(e)}}function D4(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?y4(i.stdout):b4(Qe(i))}const O4=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Vi}://probe"));u.isNil() ? "" : u.path.js`;async function k4(e){let t=await l4(e);if(t.kind!==`ok`)return b4(pr(t).split(`
|
|
482
|
+
`).join(` — `));let n=u4(t.value,[`handlerProbes`]);if(n!==null)return b4(n);let r=[];for(let e of t.value.handlerProbes){let t=A4(e);if(t===null)return b4(`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 y4({arrivals:r})}function A4(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 j4(e,t){let{host:n,clock:r}=t;return{platform:process.platform,sockets:{own:pn(n),handler:mn()},monotonic:()=>r.monotonic(),nonce:le,daemon:()=>k4(t),open:t=>{let n=D4(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>Re(r,100),opener:()=>{let t=D4(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,O4]);if(t.kind===`failed`)return t;let n=t.value.trim();return y4(n===``?null:n)},exists:s.existsSync}}function M4(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 N4(e){let t=M4(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const P4=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function F4(e){let t=M4(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function I4(e){return FQ(()=>decodeURIComponent(e))}const L4=5e3;function R4(e,t,n){if(e.reason===`rate-limited`){n(`warn`,Qe(e));return}throw e.reason===`aborted`?new NQ(t):Error(`${t} failed (${Qe(e)})`)}async function z4(e,t,n,r,i,a){let o=p(T.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:T.join(o,`stderr`),status:T.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){R4({...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=At(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;R4(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 Re(e.clock,50)}}finally{_(o,{recursive:!0,force:!0,maxRetries:3})}}function B4(e,t){V4(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function V4(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const H4=async(e,t)=>B4(I4(e),t),U4=new Set([`request`,`feed`]);function W4(e){if(!U4.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const G4=async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n),o=t.diagnosticCopy(a,W4(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);B4(o,t)},K4=async(e,t)=>V4(t,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,I4(e)],category:`click.open`},`open -a "Visual Studio Code"`),q4=async(e,t)=>{let n=F4(I4(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},J4=async(e,t)=>{let[n=``,...r]=FQ(()=>Ca(e)),i=F4(n),a=t.gates.state.gateFor(o3(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})}Q4(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})`)},Y4=/^-?\d+$/;function X4(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const Z4=async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Y4.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=o3(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&&Y4.test(u)?$4(l,parseInt(u,10)):e3(`step-state`,r,l,s$(s,e=>t.sessionState.get(a,e),r)),f=X4(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);Q4(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 Q4(e,t,n,r){let i=r.filter(e=>e.key.startsWith(GN));if(i.length===0)return;let a=XQ(o3(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function $4(e,t){return Math.max(e.min,Math.min(e.max,t))}function e3(e,t,n,r){if(r===null)return n.min;if(!Y4.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return $4(n,parseInt(r,10))}function t3(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function n3(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:t3(a,i)}}function r3(e,t){let n=i3(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function i3(e,t){let n=e.sessionState.get(t,KU);return n===null?null:n3(n)}function a3(e,t,n){let r=i3(e,t);if(r===null)return;let{path:i}=l3(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function o3(e,t){return e.configFor(r3(e,t))}function s3(e,t){let n=i3(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function c3(e,t){let n=i3(e,t);return n===null?l$:p$(e.configFor(n))}function l3(e,t){return sU(e.locations,VU(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function u3(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const d3=async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n),o=r3(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=l3(t,o),d=JQ(s,e=>t.sessionState.get(a,e),r);i1(u3(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},f3=async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Y4.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=r3(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=l3(t,s),f=JQ(c,e=>t.sessionState.get(a,e),r),p=r1(d.path,f.key),m=typeof p==`number`?$4(u,p):e3(`step-config`,r,u,c$(f.globals,r)),h=X4(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);i1(u3(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})`)},p3=async(e,t)=>{let[n=``]=FQ(()=>Ca(e)),r=F4(n),i=r3(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=KQ(a,o),c=YQ(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]});h3(`save`,l,c);let d=l3(t,i);a1(u3(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(m3)].join(` `)} → ${d.path} (session=${r})`)},m3=e=>`${e.preset}/${e.id}.settings.${e.setting}=${ab(e.value)}`;function h3(e,t,n){for(let r of n){let n=t.validate(r.key,ab(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const g3=async(e,t)=>{let[n=``]=FQ(()=>Ca(e)),r=F4(n),i=r3(t,r),a=t.configFor(i),o=$Q(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]});h3(`save-preset`,s,o.placements);let l=l3(t,i),u=f1(u3(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Lx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Fx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(m3)].join(` `)} → ${l.path} (session=${r})`)},_3=async(e,t)=>{let[n=``]=FQ(()=>Ca(e)),r=F4(n),i=r3(t,r),a=t$(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=l3(t,i);p1(u3(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(KQ(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Ax.map(e=>Fx[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} ${Ax.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},v3=async(e,t)=>{let[n=``,r=``]=FQ(()=>Ca(e)),i=F4(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=r3(t,i),o=l3(t,a);m1(u3(t,i),o,r),t.reloadConfig(a);let s=Fx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},y3=async(e,t)=>{let[n=``,...r]=FQ(()=>Ca(e)),i=F4(n),a=r3(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=l3(t,a),l=r.map(n$),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);l1(u3(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 b3(e,t){let n=(e,t)=>[...zy(gS(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(pS(t.presets).flatMap(e=>n(t,e).map(t=>KN(wM(e),Fy(t)))));return pS(e.presets).flatMap(t=>n(e,t).map(e=>({member:KN(wM(t),Fy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function x3(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[HN]:[]])}const S3=async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n),o=r3(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=ez(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=l3(t,o),f=h1(u3(t,a),d,r,u);t.reloadConfig(o);let p=x3(b3(s,t.configFor(o)),t.sessionState.get(a,HN)).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})`)},C3=async(e,t)=>{let[n=``]=FQ(()=>Ca(e)),r=F4(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),a3(t,r,i),t.log(`info`,`undo: restored ${B1(i)} (session=${r})`)},w3=async(e,t)=>{let n=F4(I4(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(o3(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},T3=async(e,t)=>{let n=F4(I4(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);a3(t,n,r),t.log(`info`,`rewind: put back ${B1(r)||`nothing`} as edit mode found it (session=${n})`)},E3=async(e,t)=>{let[n=``]=FQ(()=>Ca(e)),r=F4(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),a3(t,r,i),t.log(`info`,`redo: re-applied ${B1(i)} (session=${r})`)},D3=async(e,t)=>{F4(I4(e)),t.effect({kind:`apply-update`})};function O3(e,t){let n=e.sessionState.get(t,qU);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 Bn(r)}function k3(e,t,n){let r=YF(n);e.sessionState.setBatch(t,fI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${$F(n.config)} ${uI(n.nerdFont,n.marks)} ${eI(n.terminal,n.clicked)} ${tI(n.terminal,n.width)} ${nI(n.install)} ${iI(n.daemon)} ${aI(n.data)} ${lI(n.transcripts)} ${oI(n.frames,n.claudeSettings)} ${cI(n.claudeSettings.origin.sources)} (session=${t})`)}async function A3(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 t4({...n,loadConfig:()=>r},O3(e,t),r3(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:s0(i,a)},e4(t,a),D2(e.doctorStores))}catch(e){throw e instanceof r0?new Z(e.message):e}let s={facts:o,install:T2(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(r3(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:A3(e,t,n,i)}};return s}const j3=(e,t)=>{let n=O2(e.doctor);return A3(e,t,n,n.loadConfig(r3(e,t)))};async function M3(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=D2(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:Z2(e.arrival),install:i,clicked:N3(e,o)}}function N3(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?dF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>t0(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 P3={gathers:!0,prepare:async(e,t)=>{let n=F4(I4(e)),r=await j3(t,n);return async e=>k3(e,n,await M3(e,n,r))}},F3=async(e,t)=>{let n=C4(I4(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}`)},I3={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=FQ(()=>Ca(e)),i=F4(n),a=XF(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await j3(t,i);return async e=>{let t=await M3(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=n4(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} → ${Qte(n.fix)} (session=${i})`),k3(e,i,r.value)}}},L3={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=FQ(()=>Ca(e)),a=F4(n),o=XF(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!hF.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${hF.join(` or `)}`);let s=await j3(t,a);return async e=>{let t=await M3(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=>Q1(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})`),k3(e,a,{...t,marks:c})}}},R3=async(e,t)=>{let[n=``,r=``]=FQ(()=>Ca(e)),i=F4(n),a=Object.values(t.configFor(r3(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=SQ(O3(t,i).tmux);if(s.kind===`refused`)throw new Z(`${r} was not typed: ${s.reason}`);t.effect({kind:`type-slash`,pane:s.hint,line:o.slash})};function z3([e=``,t=``,n=``,r=``],i){let a=F4(e),o=r3(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=kS(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:{...Y1({sessionId:a,projectDir:o.projectDir,claudeConfigDir:O3(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const B3=new Map([[Ki,P4(H4)],[qi,P4(K4)],[Wi,P4(J4)],[Gi,P4(Z4)],[Yi,P4(d3)],[Xi,P4(f3)],[ta,P4(y3)],[Zi,P4(p3)],[Qi,P4(g3)],[$i,P4(_3)],[ea,P4(v3)],[na,P4(S3)],[ra,P4(C3)],[ia,P4(E3)],[aa,P4(w3)],[oa,P4(T3)],[Ji,P4(q4)],[sa,P4(D3)],[ca,P3],[la,I3],[ua,L3],[da,P4(F3)],[fa,P4(R3)],[`run`,P4(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=FQ(()=>Ca(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=z3(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[pa,P4(async(e,t)=>{let[n=``,r=``,i=``,a=``]=FQ(()=>Ca(e)),o=F4(n),s=i;if(!t.links.verify(UU(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=HU(VU(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(r3(t,o))})],[ma,P4(G4)]]),V3=new Set([Wi,Gi,Yi,Xi,ta,Zi,Qi,$i,ea,na,ra,ia,aa,oa,Ji,sa,ca,la,ua,fa,`run`,pa,ma]);function H3(e,t){return U3(e===`dispatch`?Ea(t):[{verb:e,value:t}])}function U3(e){let t=e.find(e=>V3.has(e.verb)),n=t===void 0?``:FQ(()=>wa(t.value));return n===``?null:M4(n)}const W3=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function G3(e,t,n,r){let i=r??await n.gather(n=>e.prepare(t,n)),a=[];await i({...n,effect:e=>void a.push(e)});for(let e of a)n.effect(e)}async function K3(e,t){let[n]=Oa(Ea(e)),r=n===void 0?void 0:B3.get(n.verb);return r?.gathers?W3(r,n.value,t):void 0}async function q3(e,t,n){let r=[],i=!1,a=Ea(e),o=U3(a);for(let[e,{verb:o,value:s}]of Oa(a).entries()){let a=B3.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await G3(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof NQ)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&&Sc(t.sessionState,o.id,r.join(`
|
|
483
|
+
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function J3(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function Y3(e,t,n,r){let i=e===null?null:s3(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)}J3(e)}),c=[],l=e=>g$(e,e=>c3(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d=[];try{await r({...u,effect:e=>void d.push(e),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)}f&&t.described(d),J3(c)}function X3(e,t,n){return async(r,i)=>{let a=H3(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,i.asker,()=>t(r,i),(e,t)=>Y3(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const Z3=new Map([...[...B3].map(([e,t])=>[e,X3(e,async(e,n)=>t.gathers?W3(t,e,n):void 0,(e,n,r)=>G3(t,e,n,r))]),[Ui,X3(Ui,K3,q3)],[da,F3]]);Object.freeze([...Z3.keys()]);function Q3(e){let t=Z3.get(e);return t===void 0?null:{name:e,run:t}}function $3(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>Y3(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=h$(c3(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:P}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}const e6=[],t6={request:async({req:e,at:t,waitEndsAt:n,facts:r},i)=>({answer:await sQ(i,e,t,n,r),effects:e6,facts:[]}),click:async({verb:e,value:t,arrival:n,pending:r,asker:i},{verbCtx:a,menuIdle:o})=>{r!==null&&o.clickArrived(r);let s=[],c=null;try{await e.run(t,{...a,arrival:n,asker:i,described:e=>void s.push(...e)})}catch(e){c={error:e}}finally{r!==null&&o.clickSettled(r)}return{answer:c,effects:s,facts:[]}},"menu-idle":async({session:e,idle:t},{verbCtx:n})=>{let r=[];return await $3(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":async({of:e,outcome:t},{verbCtx:n})=>{let r=[];return await n.journalTurns.take(`effect-done`,{waited:e=>r.push([`turnWait`,`${e}ms`]),gone:()=>!1},async()=>{t.kind===`failed`&&e.session!==null&&Sc(n.sessionState,e.session,t.said,n.now())}),{answer:void 0,effects:e6,facts:r}}};async function n6(e,t){let n=t6[e.kind],r=await n(e,t),i=l6(e),a=s6[e.kind],o=a(e,r);return o!==null&&t.log(o.level,qZ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>MQ(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?r6:p6(t,i,r.effects)}}const r6=Promise.resolve(),i6={level:`info`,facts:[[`outcome`,`ok`]]},a6=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),o6={ok:`info`,failed:`warn`},s6={request:()=>null,click:(e,{answer:t})=>t===null?i6:a6(t),"menu-idle":()=>i6,"effect-done":({effect:e,outcome:t})=>({level:o6[t.kind],facts:[[`effect`,MQ(e)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},c6={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({verb:e,pending:t})=>({verb:e.name,session:t}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e};function l6(e){let t=c6[e.kind];return t(e)}const u6={launch:({spec:e,what:t},{verbCtx:n})=>d6(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await CQ(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:AQ(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),kQ)};async function d6(e,t,n){let r=await e.launch({...t,timeoutMs:L4});return r.ok?kQ:AQ(`${n} failed (${Qe(r)})`)}async function f6(e,t){let n=u6[e.kind];try{return await n(e,t)}catch(e){return AQ(e instanceof Error?e.message:String(e))}}function p6(e,t,n){return e.verbCtx.journalTurns.performing(t.session,async()=>{for(let r of n){let n=await f6(r,e);try{await n6({kind:`effect-done`,of:t,effect:r,outcome:n},e)}catch(t){e.log(t instanceof NQ?`info`:`error`,`apply: effect-done not applied (${MQ(r)} ${n.kind}: ${n.said}): ${x(t)}`)}}})}const m6=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`]),h6=[[`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`]],g6=[[`workspace.added_dirs`,`string-list`]];function _6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of h6){let i=b6(n,e);if(i==null)t.missingRequired.push(e);else{let n=v6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of g6){let i=b6(n,e),a=i===void 0?r:y6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))m6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function v6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function y6(e){return Array.isArray(e)&&e.every(e=>v6(e)===`string`)?`string-list`:v6(e)}function b6(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 x6(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:_P(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function S6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Rn.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Rn.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function C6(e,t,n,r){let{report:i}=_6(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=M4(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!D(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=S6(e.encoding);s.ok||a.push(s.problem);let c=mr(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=Bn(e),{configFile:u,refusedArgs:d}=x6(e.args,e.cwd,r);return{ok:!0,req:{...e,deadline:c,encoding:s.encoding,sessionId:o.id,hints:l,rateLimits:Lte(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:bP(u,l.configEnv)},refusedArgs:d}}}function w6(e,t){switch(e){case`vars`:return{what:e,vars:T6(t)};case`segments`:return{what:e,segments:A6(t)};case`config`:return{what:e,config:P6(t)}}}function T6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=O6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=E6(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:D6(r.lastUpdatedMs(),t.clock)})}return o}function E6(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 D6(e,t){return e===null?null:Math.max(0,t.now()-e)}function O6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,k6(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}`,k6(i));return t}function k6(e){return e.kind}function A6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=M6(n),o=j6(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:N6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function j6(e){let t=new Map;for(let n of pS(e.presets))for(let r of zy(gS(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Fy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function M6(e){let t=[],n=new Set;for(let r of zy(tS(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 N6(e,t,n){let r=new Set([...eC(e,t).keys()].flatMap(e=>vC(e,n)));return Array.from(r).sort()}function P6(e){return e===null?null:e.config}const F6=[`vars`,`segments`,`config`];function I6(e){return typeof e==`string`&&F6.includes(e)}const L6=e=>({resp:e,exitAfterFlush:null,delivered:JZ}),R6=e=>({kind:`reply`,...e}),z6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},B6=(e,t)=>R6(L6({ok:!1,error:t,code:e,daemonV:3}));function V6(e){let t=M4(e.sessionId);if(!t.ok)return B6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return B6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${ix.join(`, `)}): it predates the lane toggles — update it`);let n=fx(e.lane);return n===null?B6(`BAD_REQUEST`,`subscribe needs a lane, one of ${ix.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function H6(e,t,n,r,i){if(t.kind===`url`)return R6(L6(await X6(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?B6(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?V6(a):typeof a.kind!=`string`||!Object.hasOwn(z6,a.kind)?B6(`BAD_REQUEST`,`unknown kind`):R6(await U6(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,delivered:JZ})}async function U6(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:ee,sourceDigest:w,doctorStores:te}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:JZ};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return L6(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 L6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:W6(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:Vo(),renderCache:c.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(He(new Date(o.now()))),bundle:ee,sourceDigest:w,daemon:b.serving(),doctorStores:D2(te)})});if(t.kind===`render`){let c=new Date(o.now()),l=He(c),u=o.monotonic(),d=Ie(r,u),f=[],p=++a.requestsTotal,m=C6(t,a,e.log,e.home),h=(t,n)=>C.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Qo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Rte(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await n6({kind:`request`,req:m.req,at:l,waitEndsAt:Fe(u,hr(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({answer:{resp:t,motion:n,clickShown:r,pipeShown:i,delivered:a}})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r!==null&&Cc(_,m.req.sessionId,r),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:YZ(e),delivered:JZ})):n8(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,UZ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=KZ(`render`,f,g.outcome,A(o,u));return e.log(v,y),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return L6(await J6(e,r,n,i,(n,r)=>Y6(e,t,n,r)));if(t.kind===`debug`){if(!I6(t.what))return L6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${F6.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`?q6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Mx(`colorCompatibility`)):K6};return L6({ok:!0,debug:w6(t.what,n)})}throw Error(`no reply for request ${x(t)}`)}function W6(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 G6={endcaps:Mx(`endcaps`),colorCompatibility:Mx(`colorCompatibility`),wrap:Mx(`autoWrap`),padding:Mx(`padding`),width:1/0},K6=new Map;function q6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Nte(i,{...G6,colorCompatibility:t}));return n}async function J6(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Ie(t,o)}ms`]],c=await i(s,()=>n()||r());UZ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=KZ(`click`,s,c,A(a,o));return e.log(l,u),e8(c)}async function Y6(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};UZ(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}`]}:Z6(()=>$6(e,a,o,i,n,r))}async function X6(e,t,n,r,i){return J6(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(UZ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Zn.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${x(i)} is not one this daemon speaks (${[...Zn].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 Z6(()=>$6(e,o.verb,o.value,s,n,r))})}async function Z6(e){try{return await e()}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof NQ?{kind:`closing`,error:e}:e instanceof PQ?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const Q6={link:`verb`,"tmux-status":`linkVerb`};async function $6(e,t,n,r,i,a){if(t===`tmux-status-click`)return UZ(i,{verb:t}),t8(e,n,i,a);let o=Q3(t);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};UZ(i,{[Q6[r.via]]:t});let s=H3(t,n),c=s?.ok?s.id:null;s===null?UZ(i,{sid:`-`}):c!==null&&UZ(i,{sid:c});let{answer:l}=await n6({kind:`click`,verb:o,value:n,arrival:r,pending:c,asker:{placed:e=>UZ(i,{placeWait:`${e}ms`}),gathered:e=>UZ(i,{gather:`${e}ms`}),waited:e=>UZ(i,{turnWait:`${e}ms`}),gone:a}},e);if(l!==null)throw l.error;return{kind:`ok`}}function e8(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 YZ(e.error)}}async function t8(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(UZ(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`):$6(e,t.verb,t.value,{via:`tmux-status`},r,i):o(t.problem)}return await z4(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,L4,e.tmp),{kind:`ok`}}const n8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:JZ});function r8(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return T.join(e,`update-act`,n)}const i8={kind:`idle`};function a8(e){if(e===null)return i8;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 o8=e=>({stdout:T.join(e,`stdout`),stderr:T.join(e,`stderr`),status:T.join(e,`status`)}),s8=e=>T.join(e,`record.json`);function c8(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 l8(e){let t=Yo(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 u8(e,t){let n=T.join(e,`.removed-${t}-${process.pid}`);try{s.renameSync(T.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}s.rmSync(n,{recursive:!0,force:!0})}const d8=e=>e.now()-o.uptime()*1e3;async function f8(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 p8(e){try{return JSON.parse(s.readFileSync(s8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const m8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function h8(e,t,n,r){let i=null;async function a(a){let o=T.join(e,String(a)),c=p8(o);if(c===null)return null;if((i===null||!m8(i.record,c))&&(i={record:c,ours:await f8(c,t,n,d8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=o8(o),u=At(l.status),d=u===null?null:l8(l.stderr)??l8(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=c8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${T.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function g8(e,t,n){s.mkdirSync(e,{recursive:!0});let r=s.mkdtempSync(T.join(e,`.claim-`));try{return s.writeFileSync(s8(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 _8(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=T.join(t,String(c)),u=e.launchJobSync(i,o8(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!g8(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return v8;if(c8(t).some(e=>e>c))return u8(t,c),v8;d=!0}finally{d?u.release():u.withdraw()}for(let e of c8(t).filter(e=>e<c))u8(t,e);return{ok:!0,act:c}}const v8={ok:!1,reason:`another act claimed this bundle first`};function y8(e,t,n){let r=o8(T.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function b8(e,t,n){if(t.kind===`pending`)return Ao(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,Y.compareStructural)(r,t))return e}return{...t,at:n}}var x8=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 S8(e){return e.kind===`source`?e.newer.digest:ms(e.newer)}const C8=e=>`${e.version} [${tn(e.digest)}]`;function w8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:C8(e.newer),running:C8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:ms(e.newer),running:ms(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${gs}@${ms(e.newer)}`,`install`]}}}}function T8(e,t,n){if(e===null)return[];let r=S8(e);if(!n.enabled||n.dismissed===r)return[];let i=w8(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
484
|
+
`),c=t.kind===`running`?_U(`[${i.busy}]`,null):_U(`[${i.act}]`,Ta([{verb:sa,args:[n.sessionId]}])),l=[_U(a,null),c,_U(`[dismiss]`,Ta([{verb:Wi,args:[n.sessionId,jz,r]}])),_U(`[disable]`,Ta([{verb:Yi,args:[n.sessionId,Mz,`false`]},{verb:Wi,args:[n.sessionId,Nz,`false`]}]))],u=o.map(e=>[_U(e,null)]);return[{severity:mU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function E8(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return I({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return L;case`unchecked`:return R(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return D8(t)}}function D8(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return I({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return L;case`unchecked`:return R(`release: unchecked: ${t.reason}`,`read`)}}function O8(e){switch(e.kind){case`current`:return[`info`,`build: current ${C8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${C8(e.source)}, running ${C8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function k8(e){switch(e.kind){case`current`:return[`info`,`release: current ${ms(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${ms(e.latest)}, running ${ms(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${ms(e.installed)}, latest ${ms(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function A8(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=Ao(`unread`),g=Ao(`unread`),_=async e=>{let t=await i.startTime(e);if(w)throw new NQ(`apply-update`);return t},v=h8(s,_,r,n),y=null,b=null,x=Ne(m),S=Ne(m),C=new x8,ee=e=>C.run(`acts`,e),w=!1,te=[],ne=(e,t)=>{te.push(n.every(t,e,{unref:!0}))},T=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function re(){let e=T(),t=e===null?null:S8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(jz,[t])})}function E(){let e=w?L:E8(h,g),r=b8(t.get(),e,We(n));(0,Y.runInAction)(()=>t.set(r)),re()}function D(){let e=cn(a,()=>an(o));return h=I(e),x(O8(e)),E(),e}async function ie(){let e=vs(nn,await _s(gs,d,u,n));g=I(e),S(k8(e)),E()}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 NQ?{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}=y8(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 w||se(e),e});if(w||!e.ok)return;let t=a8(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`),D(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await ee(ce),!w&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=D();ne(D,c),te.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),ne(()=>void ie(),l))},close(){w=!0,E(),te.forEach(e=>e())},notice:e=>T8(T(),y??i8,e),running:()=>ee(async()=>{let e=await oe(()=>v.read());return e.ok&&a8(e.value).kind===`running`}),error:()=>O,act:()=>ee(async()=>{if(w)throw new NQ(`apply-update`);let e=await oe(()=>v.read());if(w)throw new NQ(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=T();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=w8(t),a=e.value;if(a8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await _8(r,s,a===null?null:a.act,S8(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 j8(){return Y.observable.box(Ao(`unread`),{deep:!1})}function M8(e,t){try{return I(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?L:R(e.message,`read`)}}function N8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function P8(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:M8(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=M8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!N8(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 F8=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 I8=`pass`,L8={okMs:5*6e4,failedMs:45e3},R8=L8.okMs;function z8({failures:e}){return vj(L8,e,R8)}function B8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function V8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function H8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function U8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:T.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Yc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${Xc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function W8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function G8(e){e.missed=!0,Cj(e,`unread`)}function K8(e,t){return e.missed&&e.reading.get().kind===`pending`&&Sj(e,t.size>0?R([...t].join(`; `),`read`):L),`unkeyed`}function q8(e,t){let n=Ej(e);return t===null||n.kind!==`ok`?n:I({...n.value,pullRequest:Ej(t)})}const J8=R(`git cache closed`,`read`);function Y8(e){return t=>R(`${e} threw: ${String(t)}`,`read`)}var X8=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 Mo(e.maxPrLookups??2),this.logger=e.logger??Pe;let t=e.ledger??new Ij(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 gj({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=R(`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={},r){let i=this.asked(e,t,n,r);if(i.kind===`settled`)return kj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>q8(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:J8};let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`settled`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.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))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new F8,watch:this.followWatch(e,null).watch,period:new yj(()=>{n.refresh.share(I8,()=>this.refreshPass(n))},this.clock),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=U8(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(I8,()=>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,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&G8(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(I8,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:bj(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=H8(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(V8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}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=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(Y8(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,Sj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of zq(n.value))c.add(e)});let l=W8(o),u=a===null||i.length===0?`-`:l===void 0?K8(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,B8(n),c.size===0?I(null):R([...c].join(`; `),`read`),A(this.clock,t))}prSource(e){let t={period:new yj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:L,reading:bj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(Y8(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(G8(t),`owed`):(Cj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Sj(t,a.outcome),t.period.landed(z8(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(Y8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:L)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(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||(Sj(t,i),t.period.landed(z8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=R(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())wj(n,t);e.pr!==null&&wj(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()}},Z8=class{static usageDir(e){return T.join(e,`usage`)}static locksDir(e){return T.join(e,`locks`)}static isLocked(e,t){let n=T.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=T.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 Re(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=T.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=T.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 Re(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 Re(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=T.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 Q8={"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 $8=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 Z8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await Z8.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(Q8).length} models`),this.executionCache=Q8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(Q8).length} models`),Q8)}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`}},e5=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 t5(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 n5={okMs:60*1e3,failedMs:10*1e3},r5={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function i5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function a5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const o5={entries:0,cost:0,breakdown:a5(),days:new Map};async function s5(e,t,n,r){let i=AX(new Date(i5(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 $8.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=AX(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...OX};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 c5(e){let t=0,n=0,r=a5(),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)??{...OX};kX(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:r5,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function l5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function u5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!l5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...OX};kX(r,t),n.set(e,r)}return Object.fromEntries(n)}async function d5(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 f5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function p5(e,t){(0,Y.runInAction)(()=>e.set(t))}var m5=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new e5;scans;daySets=new Map;speedFlight=new e5;requestFlight=new e5;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 Ij(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new jj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??n5,watch:Aj,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()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Po(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:I(f5(t.kind===`ok`?t.value.sessionInfo:r5,e))},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Ao(`unread`);let r=n.failure.get();return r===null?I(f5(n.record?.sessionInfo??r5,t)):R(r,`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=${z(e)}`,`request`,a,A(this.clock,i)),p5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e){return this.request(e?.session_id??``,e?.transcript_path).today()}declareToday(e,t){if(this.closed)return kj(R(`usage store closed`,`read`));let n=_0(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?I({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return L;let r=n.failure.get();if(r!==null)return R(r,`read`);let i=n.record;return i===void 0||l5(i.transcriptPath,t)?L:I(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return L;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=t5(t.kind===`ok`?t.value.sessionInfo.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=I({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return p5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Ao(`unread`):L}async ingest(e,t,n,r){if(!e)return L;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,I(i);if(!t)return i?I(i):L;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 R(`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,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),I(c)):l===void 0?I(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,Y.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:Y.observable.box(null),speed:Y.observable.box(void 0,{deep:!1})};return(0,Y.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 PC(`today over ${e.join(`,`)}`,()=>u5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await b0(e,E(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of k0(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 A0(e,r,o5,(e,t)=>s5(e,t,dn(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 k0(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return I({files:i,...c5(i),mainStamp:a})}async scan(e){try{let t=i5(this.clock.now()),n=await v0(e),r=[];for(let e of n){let n=await y0(Ro(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await y0(zo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Fo(a)})}}let i=[],a={hits:0,misses:0};return await d5(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=${z(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?R(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):I({sessions:r.length,read:a.misses})}catch(e){return R(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=AX(new Date(e)),n=0,r=0,i=0;return(0,Y.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,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},h5=class{values=Y.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,Y.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)}})}},g5=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 h5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Po(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 A0(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(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 k0(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Ao(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function _5(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 v5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new g5(void 0,_5,(e.ledger??new Ij(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return k(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);k(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?I(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,y5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return I(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,y5(e))}contextFrom(e,t){if(e.kind===`failed`)return R(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),L):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),I({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function y5(e){return e.context_window?.context_window_size??2e5}const b5={messageCount:0,nonPrompts:0,recent:[]},x5=new Set([`turn`,`interrupt`,`claude-code`]);function S5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!x5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function C5(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 w5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new g5(b5,S5,(e.ledger??new Ij(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?T5(e,n,await this.fold.read(e,t.transcript_path)):L}metricsOf(e,t){let n=t.cost;if(!n)return L;let r=this.fold.answer(e);return r.kind===`pending`?r:T5(e,n,r)}};function T5(e,t,n){return n.kind===`failed`?R(`metrics (${e}): ${n.reason}`,n.failedAt):I({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:C5(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const E5={command:null,todos:[],pending:[],done:[]};function D5(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 O5(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 k5(e,t){if(t.isSidechain)return e;let n=O5(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=D5(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 A5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>D5(e,t.name),[]),done:e.done}}var j5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new g5(E5,k5,(e.ledger??new Ij(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return M5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:M5(e,t)}};function M5(e,t){return t.kind===`failed`?R(`activity (${e}): ${t.reason}`,t.failedAt):I(A5(t.value))}const N5=3e4;var P5=class{names;constructor(e){let t=e.logger??Pe;this.names=new jj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>F5(e.launcher,t),every:()=>({okMs:N5,failedMs:N5}),watch:Aj,maxEntries:64,logger:t,ledger:e.ledger??new Ij(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function F5(e,t){let n=await bc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return R(n.reason,`read`);let r=n.stdout.trim();return r?I(r):L}const I5=6e4,L5={okMs:I5,failedMs:I5};function R5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function z5(e,t){try{let e=t();return Promise.resolve(e===``?L:I(e))}catch(t){return Promise.resolve(R(`host.${e}: ${String(t)}`,`read`))}}var B5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>L5,watch:Aj,maxEntries:1,logger:t,ledger:e.ledger??new Ij(t),clock:e.clock};this.name=new jj({...n,name:`host.name`,read:()=>z5(`name`,()=>R5(o.hostname()))}),this.user=new jj({...n,name:`host.user`,read:()=>z5(`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()}},V5=class{known=new h5(64);refreshes;constructor(e,t=Pe,n=new Ij(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=H5(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=AI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Ao(`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 H5(e){try{let t=s.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Fo(t)}catch(e){return`unread:${e.code??`error`}`}}const pne=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function mne(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 hne=class{known=new h5(256);refreshes;constructor(e,t=Pe,n=new Ij(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Po(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??Ao(`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 gne(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,A(this.clock,r)),i}};async function gne(e){let t=await _ne(e);return t.kind===`ok`?I(Math.floor((t.value+36e5)/1e3)):t}async function _ne(e){for(let t of[65536,1048576]){let n=await Jo(e,t);if(n.kind!==`ok`)return n;let r=vne(n.value.buf,n.value.fromStart);if(r!=null)return I(r);if(n.value.fromStart)return L}return L}function vne(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!pne.test(t))continue;let r=mne(t);if(r!=null)return r}return null}const U5=e=>oH(e),W5=e=>T.join(e.storage.folder,U5(e.sessionId)),G5=e=>JSON.stringify([e.folder,e.generation]),K5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var yne=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??Kc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new jj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(W5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Aj,maxEntries:256,logger:e.logger,ledger:e.ledger??new Ij(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`||!qc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${z(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(G5(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:${G5(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(G5(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=G5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>K5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(T.join(n.folder,T.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(W5(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`&&qc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${z(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>K5(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=${z(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>K5(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(G5(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=il(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 R(t,`read`);let n=W5(e),r;try{r=await s.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?L:R(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return L;let i=Wj(r);return i.kind===`failed`?R(`${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=${z(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=T.join(e.folder,a.name);try{let{mtimeMs:r}=await s.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&U5(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 bne(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new B5({clock:n,logger:r,ledger:i}),gitProvider:new X8({inner:new pJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new m5({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new v5({clock:n,logger:r,ledger:i}),metricsProvider:new w5({clock:n,logger:r,ledger:i}),activityProvider:new j5({clock:n,logger:r,ledger:i}),tmuxService:new P5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new V5(n,r,i),cacheExpiry:new hne(n,r,i),managedStorage:new yne({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new FX,log:e.logger,clock:n}}function*q5(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*xne(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 pS(e.presets)){for(let n of zy(gS(e,t).node))n.when!==void 0&&(yield n.when);let n=yS(e,t);for(let e of ny){let t=n[e];ry(t)&&(yield t)}}for(let[,t]of q5(e))for(let[,e]of Jy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of AS(t))yield e}function Sne(e,t,n){let r=UG(t),i=new Set,a=new Set,o=new Set;for(let e of xne(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of iC(e,t.helpers))a.add(n);for(let n of fC(e,t.helpers))o.add(n)}for(let[,e]of q5(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 pS(t.presets))for(let n of zy(gS(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(q5(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 Cne(e){return Math.floor(Math.max(e/4,e*Vr-67108864))}const wne={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function J5(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[aH(PS(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[PS(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>FS(e)(t)&&t!==aH(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${SP(e,`<default>`)}: projections=${[...iq(n).keys()].join(`,`)||`-`} instantSegments=${Sq(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 Tne=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Ene=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${Tne(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Dne(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.projectDir)} cwd=${z(e.cwd)} cause=${z(Ene(t))} state=${n} files=${z(SP(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 One(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function kne(e,t,n){return e+`\0`+t+`\0`+(n??``)}function Ane(e,t){return new Set(pS(e.presets).filter(n=>gS(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function jne(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,T.join(e.projectDir,zH)])];return lj({named:[...$H(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 Mne(e){return e.filter(Boolean).join(`
|
|
486
|
+
`)||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 Nne(e){let{loaded:t,chain:n}=e;return zj({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 Pne(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=$Y(t.locs,t.layers,TX,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Pne(i.config,n)};return{kind:`resolved`,...a,key:Nne(a),warnings:r}}catch(e){return e instanceof db&&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??TX,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new WC(t.clock),m=new fM(t.runs,p,o.globals.default_empty_value??``,t.sessionState),h;try{h=gq(o,m,n,t.compile??hq(t.signer),Ine),f.push(...h.loadWarnings);let r=m.view();f.push(...yq(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 db&&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,neededInputPaths:YX(o),authoredRoots:Ane(l,u),fileHeldSettings:r$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Sne(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=>Mne([...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 Fne(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=rU(r.locations,VU(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 Fne({repos:s,advisories:[uU(r.locations,e,t),cU(o),XH(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 Ine=new Set([`directory`]),n7=new Set([`view`]);function Lne(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new aj;yq(e.config,l,t,n7);let d=()=>MZ(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),oZ(R(`view declaration threw: ${String(t)}`,`read`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=Y.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,Y.runInAction)(()=>m.set(r))},g=(0,Y.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=[],v=()=>{g();for(let e of _)e();return u.close(),l.dispose()},y;try{y=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get(),onDispose:e=>_.push(e)})}catch(e){throw v(),e}PK(e.compiled,l.variableStore,l,y);let b=(0,Y.reaction)(()=>[y.payload(),y.selections(),l.published(),e.registry.published()],()=>o(c),{equals:Y.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:y,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:b,dispose:()=>(b(),v())}}var Rne=class{entries=new Map;answersWatch;stopSweep=null;closed=!1;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(zU(e.stateDir),{recursive:!0});let{dir:n,name:r}=oj(BU(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)??xq(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=kne(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`,J5(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=${Ir(this.accountedBytes())}/${Ir(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++,this.armSweep();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 o.read=!0,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}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{sessionId:i}=n,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=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=Lne(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}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}`))}armSweep(){this.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.releaseIdle(),{unref:!0}))}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.stopSweep!==null&&(this.stopSweep(),this.stopSweep=null)}close(){if(this.closed)return;this.closed=!0,this.stopSweep?.(),this.stopSweep=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.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,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=${Ir(this.accountedBytes())}/${Ir(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(),this.leaseOf(r).read,`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`,One(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){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`,J5(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.reloadInto(t,e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=jne(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 zne=e=>!S1(e)&&!vI(e)&&e!==`update.dismissed`&&e!==Bi;var Bne=class{past=Y.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:_1(e,zne,(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,Y.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,Y.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)})}};const r7=(e,t)=>e?t:Ao(`unread`),i7=(e,t)=>e.kind===`ok`?I(t(e.value)):e;function Vne(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return L;case`ok`:return e.value.pullRequest??Ao(`unread`)}}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 Hne({pullRequest:e,...t}){return t}function o7(e,t,n,r,i){let{lanes:a,gathered:o}=n,s=r7(o.git,a.git),c=(e,t)=>b8(e,t,i),l=e?.builtins,u={session:c(l?.session,r7(o.session,a.usage)),today:c(l?.today,r7(o.today,n.today)),speed:c(l?.speed,r7(o.speed,a.speed)),context:c(l?.context,r7(o.context,a.context)),metrics:c(l?.metrics,r7(o.metrics,a.metrics)),activity:c(l?.activity,r7(o.activity,a.activity)),cache:c(l?.cache,r7(o.cache,a.cache)),autocompact:c(l?.autocompact,r7(o.autocompact,a.autoCompact)),git:c(l?.git,i7(s,Hne)),pr:c(l?.pr,Vne(s)),tmux:c(l?.tmux,i7(r7(o.tmux,a.tmuxSession),e=>({session:e}))),hostName:c(l?.hostName,r7(o.hostName,a.hostName)),hostUser:c(l?.hostUser,r7(o.hostUser,a.hostUser))},d=Object.fromEntries(n.declaredSources.map(t=>[t,c(e?.sources[t],a.sources.get(t)??Ao(`unread`))])),f={builtins:u,sources:d,update:r,diagnostics:n.faults};return e!==void 0&&a7(u,e.builtins)&&a7(d,e.sources)&&(0,Y.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:1,session:t,seq:e===void 0?1:e.seq+1,...f}}const s7=(e,t)=>e.failure===t?e:{...e,failure:t};function Une(e,t,n,r){if(t.kind===`failed`)return s7(e,t.reason);try{let i=o7(e.document,r,t.readings,t.update,n);return e.failure===null&&i===e.document&&t.compose===e.compose&&t.draw===e.draw?e:{document:i,compose:t.compose,draw:t.draw,failure:null}}catch(t){return s7(e,`stamping the facts document: ${String(t)}`)}}function Wne(e){return({sessionId:t,state:n,store:r,declared:i,onDispose:a})=>{let o=n=>e.sessionState.get(t,n),s=r.derive(`session.effective`,`computed`,()=>NZ(n.config,o,e=>n.authoredRoots.has(e))),c=r.derive(`session.inputs`,`computed`,()=>{let{facts:t,lanes:r,preset:a}=i();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,neededInputPaths:n.neededInputPaths(a),deps:{...e.providers,lanes:()=>r}}}),l=r.derive(`session.readings`,`computed`,()=>lZ(c.read(),n.sources)),u=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n,neededInputPaths:r}=c.read();return{hookData:t,hints:n,neededInputPaths:r,home:e.providers.home}}),d=r.derive(`session.draw`,`computed`,()=>({effective:s.read(),configFacts:{...i$(n.config,n.fileHeldSettings,o),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),f=e.providers.clock,p=Y.observable.box({document:o7(void 0,t,l.read(),e.update(),We(f)),compose:u.read(),draw:d.read(),failure:null},{deep:!1});a((0,Y.reaction)(()=>{try{return{kind:`read`,readings:l.read(),update:e.update(),compose:u.read(),draw:d.read()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},n=>(0,Y.runInAction)(()=>{let r=p.get(),i=Une(r,n,We(f),t);i.failure!==null&&i!==r&&e.providers.log(`error`,`session facts sid=${JSON.stringify(t)}: ${i.failure}`),p.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let m=r.derive(`session.payload`,`computed`,()=>{let{document:e,compose:t,draw:n}=p.get();return mZ(e,t,n)});return{payload:()=>m.read(),effective:()=>p.get().draw.effective,facts:()=>p.get().document,hints:()=>p.get().compose.hints,failure:()=>p.get().failure,selections:()=>p.get().draw.effective}}}const c7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,l7=`#{session_id} #{client_control_mode} #{pane_id}`;function u7(e){let t=new Set;for(let n of e.split(`
|
|
487
487
|
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function d7(e,t){let n=new Set;for(let r of e.split(`
|
|
488
|
-
`)){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
|
|
488
|
+
`)){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 Gne(e,t){let n=new Map;for(let t of e.split(`
|
|
489
489
|
`)){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(`
|
|
490
|
-
`)){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
|
|
491
|
-
`).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
|
|
492
|
-
`)){let[n,a,o=``]=i.split(` `);if(n===void 0||a===void 0||a===``)continue;let s=F7(a,o,this.deps.owner);s.kind===`ours`?(t.layouts.set(n,{prior:s.prior,rows:[],status:s.status}),r.push(I7(n,this.deps.name))):this.leave(e,t,n,s.why)}await this.write(e,r)}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)} ${_7} 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,rre(n));if(r===null||this.closed)return null;let i=ire(n,r,this.deps.owner,this.deps.name);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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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=ere(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,g7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,nre(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`,...y7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${E7(`${this.deps.handler} ${ore(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,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 cre(e){try{return Ca(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),lre={"--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`)},ure={resume:`--resume`,fresh:`--session-id`};function dre(e){return[ure[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&&fre(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const fre=(e,t)=>e===t||e.startsWith(t+T.sep);function pre(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=lre[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`?mre(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(T.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(T.sep),repo:t.slice(0,n-1).join(T.sep)||T.sep}}function mre(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,hre=T.join(`bin`,`cc-candybar-native`),gre=CI(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=xQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const _re={band:{on:async(e,t,n)=>{let r=rn(t.bundle);if(r===null)throw new Z(`${rx.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=T.join(r,hre);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:vre(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=Wt(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${rx.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:xre(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=xQ(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 vre(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=xQ(e.hints.tmux),a=i.kind===`refused`?i:await SQ(n.claudeInput,i.hint,gre);if(a.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${a.reason} — or type /reload-plugins yourself`);return`installed ${J7} from ${t} and typed /reload-plugins into ${a.pane}`}const yre=new Set([Xo,_P]);function bre(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function xre(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,Gt(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}) — ${rx.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=Ere(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${rx.statusline.label} off and on again`);let s=Sre(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=pre(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=bre(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])=>yre.has(e)),m=(e,t)=>Jt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...dre(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=Cre(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}\`, ${wre[g.kind](e.sessionId)}, and its statusline follows lane B`}function Sre(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 Cre(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const wre={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Tre={"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 Ere(e){let t=gQ(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`:_Q(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Tre[t.kind]}var Dre=class{owed=new Map;setups=new b8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=ix.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}`),Sc(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await _re[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 Ore=[`request`,`feed`],Z7=new WeakMap;let kre=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=kre++;return Z7.set(e,n),n};var Are=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 Ore){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 jre=class{queue=new b8;sessions=new b8;gathers=new b8;effects=new b8;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 NQ(e);let a=this.deps.monotonic();t(Ie(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 NQ(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--}}performing(e,t){return this.effects.run(e??`clickless`,t)}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 MQ(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},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)?Hee(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=Dn(c),u=()=>He(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new i4(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 v1(_.session),y=new T1(v,p,_.history),b=Gr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),S=new b4,C=new Bte,ee=e.doctorStores,w=new hj({clock:i,counters:m,logger:p}),te=new Fj(p),ne=new nl({watchers:w,logger:p,clock:i}),T=new eM({launcher:h,clock:i,logger:p,ledger:te,watchers:w,fileEvents:ne}),re=yne({launcher:h,host:c,watchers:w,fileEvents:ne,clock:i,logger:p,ledger:te}),{gitProvider:E,usageStore:D,tmuxService:ie,hostService:O,managedStorage:ae}=re,oe=new zne,se=new pte,ce=new Mre({clock:i,now:u,close:async(e,t)=>{await t6({kind:`menu-idle`,session:e,idle:t},we)},failed:(e,t)=>p(t instanceof MQ?`info`:`error`,`menu-idle: close failed (session=${e}): ${x(t)}`)}),le=e.linkSigner,ue=new Ac({supersede:(e,t)=>ae.supersede(e,t),launch:h.launch,state:v,log:p,now:u,clock:i}),de=new Dre({edge:e.laneEdge(h,e=>pe.following(e),d.signal,g),host:{bundle:t.path,node:t.node,socket:o.socket,preload:As(t.path,c)},state:v,log:p,now:u,defer:e=>void i.defer(e)}),fe=new sre({edge:{run:(e,t,n)=>bc(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=${Ht(o.socket)}`,...[...t.node,t.path].map(Ht),`url-handle`].join(` `),owner:o.socket,name:`main`,log:p}),pe=new zZ({render:(e,t,n)=>XZ(we,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>v.revision(e),t),lanes:e=>QZ(we,e),pin:e=>{let t=ve.pin(e);return()=>{ve.stopDrawing(e,`feed`),t()}},shown:e=>me.shown(e.hints.tmux),watching:()=>me.follow(),refreshes:()=>te.totals(),periods:NZ,clock:i,instant:u,log:p}),me=new Gne({clock:i,listPanes:e=>bc(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,c7]),listClients:e=>bc(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,l7]),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 Are,_e=A8(),ve=new Lne({clock:i,runs:T,stateDir:o.state,locations:l,env:c.env,sessionState:v,watchers:w,log:p,storage:ae,signer:le,gates:s,declare:(e,t,n,r)=>sZ(re,e,t,n,r),source:Une({providers:re,sessionState:v,update:()=>_e.get(),history:e=>y.depth(e),navigation:(e,t)=>oe.depth(e,v,s.state.gateFor(t))})},{budgetBytes:()=>Sne(n),observers:{onReload:(e,t,n,r)=>{p(`info`,Ene(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`)}});ne.subscribe(e=>{switch(e.kind){case`period`:w.judge();return;case`caught-up`:ve.reloadEvery({kind:`events-resumed`,since:e.since}),pe.wakeWhere(`data`,()=>!0);return;case`moved`:pe.wakeWhere(`data`,()=>!0);return}});let ye=60*1e3,be=N8({clock:i,targets:t.targets,intervalMs:ye,stat:e.stat,held:()=>xe.running(),exit:()=>a(0),log:p}),xe=k8({fact:_e,clock:i,launcher:h,probe:g,entryUrl:t.entryUrl,digest:t.digest,actsDir:n8(o.state,t.path),intervalMs:ye,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>be.checkNow(),log:p}),Se=new jre({log:p,monotonic:()=>i.monotonic()}),Ce={gates:s,sessionState:v,stateDir:o.state,locations:l,journalTurns:Se,clickLanded:e=>ce.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>xe.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];ve.reload(...t,{kind:`doctor`});let n=ve.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:ee,probes:S,clients:C,bundle:t.path,serving:()=>b.serving(),claudeInput:e.claudeInput(h),history:y,navigation:oe,configFor:e=>ve.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>ve.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>ve.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:le,runs:ue,lanes:{of:(e,t)=>$Z(we,e,t),clicked:(e,t,n)=>lQ(we,e,t,n)},diagnosticCopy:(e,t,n)=>ve.drawnCopy(e,t,n)},we={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:ee,stats:m,handlerProbes:S,renderSightings:C,watcherRegistry:w,refreshLedger:te,fileEvents:ne,payloadProviders:re,sessionState:v,effectSessions:se,menuIdle:ce,journalTurns:Se,linkSigner:le,runs:ue,sourceRuns:T,laneSetups:de,tmuxStatusLines:fe,frameFeeds:pe,renderWarnings:ge,renderCache:ve,updateWatch:xe,limits:b,verbCtx:Ce};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),V6(we,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),H6(we,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),Ce.reloadConfig(e)},arm(){d.signal.throwIfAborted(),ne.start(o.watchProbe),be.arm(),xe.arm(),b.arm()},close(e){let t=[[`journalTurns close`,()=>Se.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>pe.close()],[`menuIdle dispose`,()=>ce.dispose()],[`updateWatch close`,()=>xe.close()],[`binaryWatch close`,()=>be.close()],[`limits disarm`,()=>b.disarm()],[`renderCache close`,()=>ve.close()],[`gitService close`,()=>E.close()],[`usageStore close`,()=>D.close()],[`tmuxService close`,()=>ie.close()],[`hostService close`,()=>O.close()],[`runs close`,()=>ue.close()],[`sourceRuns close`,()=>T.close()],[`managedStorage close`,()=>ae.close()],[`fileEvents close`,()=>ne.close()],[`watcherRegistry close`,()=>w.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;try{e=s.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return Pre(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.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(T.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(T.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:K1(e.settingsHistory,t)}}function e9(e,t,n){for(let r of(t??``).split(T.delimiter)){if(!T.isAbsolute(r))continue;let t=T.join(r,e);if(n(t))return t}return null}function t9(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 T.resolve(e)}}function Rre(e,t,n){let r=e9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:T.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 n9=2e3;async function r9(e,t,n,r){let i=await bc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function i9(e,t){if(t.ok)return t.stdout;let n=Ze(t,t.stdout);throw Error(`${e} failed (${Qe(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(`
|
|
493
|
-
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return
|
|
494
|
-
`);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=i9(`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 a9(e,t,n){return i9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function o9(e,t){let n=await bc(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 a9(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 o9(e,t),a=await a9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Gre(e,i),c=s0(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=>Re(r,e,n);return{claudeInput:DQ(e),barPanes:async t=>Vre(await r9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await r9(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 r9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void i9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:J1(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:Fz,paneClaude:t=>Kre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+n9;for(;;){let o=await o9(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 ${n9/1e3} s`);await a(100)}},launcherNode:e=>Rre(e,e=>t9(e,s.constants.X_OK),Lre),onPath:(e,t)=>{let n=e9(e,t,e=>t9(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?(i9(`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 r9(e,t,TQ(t.pane,`cc-candybar-lane`,[]),n)}}const Jre=/^[0-9a-f]{64}$/;function s9(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=>s9(e,t).toString(`hex`),verify:(t,n)=>Jre.test(n)?ue(Buffer.from(n,`hex`),s9(e,t)):!1}}function c9(e){return T.join(e,`link.key`)}function l9(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(T.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=>Lt(e,n),storage:t=>Ire(e,t,n),doctorStores:T2(e.state),doctorEdge:L2,claudeInput:DQ,probe:Qs,laneEdge:(e,t,r,i)=>qre(e,t,r,n,i),linkSigner:l9(c9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Zr(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 u9(e){if(e===void 0)return;let t=U.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===H.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=u9(t),o=u9(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=>HP(e).map(tie))}}function rie(e){return RP(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:p7(e)})};function d9(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.clock.monotonic();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`);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(tr(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),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},null,qZ)}),u=rr(r=>{let i=Qn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{c&&(e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):d(e.sessionId,e.lane))}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(JZ(t),null,qZ)}).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,qZ)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=d9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(nr(iie[i](e,t))),refused:e=>t.end(tr(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 f9=`CC_CANDYBAR_PARENT_PID`;function oie(e){let t=e[f9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${f9} 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 p9=null,m9=null,h9=null,g9=null;function _9(){if(g9===null)throw Error(`runDaemon has not started`);return g9}function v9(e,t){_9().log.log(e,t)}function cie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:on(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function lie(e){let n=En(e.host);g9={world:e,paths:n,log:new gc(n.log,e.clock)},t.on(`uncaughtException`,e=>{v9(`error`,`uncaughtException: ${e.stack||e.message}`),S9(1)}),t.on(`unhandledRejection`,e=>{v9(`error`,`unhandledRejection: ${String(e)}`),S9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{v9(`info`,`received ${e}, shutting down`),S9(0)});uie().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${x(e)}`),S9(1)}async function uie(){let{world:e,paths:n,log:r}=_9(),{host:i}=e,a=Lr(i.env);p9=await ec(t.pid,Qs(e.launcher).startTime);let o=await oc(cc(e,p9,n.registry));if(!o.decision.allow){v9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),S9(1);return}m9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),gn(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:Pz(),exit:S9});h9=c,sie({clock:e.clock,anchor:oie(i.env),probe:Qs(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,de.createServer(e=>aie(c,e)),n.socket,!1)}function b9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){v9(`error`,`server error: ${a.message}`),S9(1);return}if(i){v9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}die(e,n,r).catch(y9)}),n.listen(r,()=>fie(e,r))}async function die(e,n,r){let i=await Us(Ws(_n(r)),(t,n)=>$s(t,n,Qs(e.launcher)));if(i.kind===`attach-and-exit`){v9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}v9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){v9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),S9(1);return}}b9(e,n,r,!0)}function fie(e,n){let r=qs(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}mie(n);try{s.chmodSync(n,384)}catch(e){v9(`warn`,`chmod socket failed: ${e.message}`)}v9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Ir(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Ir(e.memoryLimitBytes)}MB`),oi(_9().paths.spawnBackoff),e.arm(),pie(n,r.identity)}function pie(e,n){Xs({bound:n,myPid:t.pid,readIdentity:()=>qs(e),readLease:()=>Ws(_n(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function mie(e){let n=Gs(_n(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const hie=e=>(t,n,r)=>yc(e,{socket:t},`tmux-status`,n,r);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(hie(_9().world.launcher)),Ks(_9().paths.lease,t.pid),m9!==null&&sc(m9,t.pid,ic,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)+`
|
|
495
|
-
`:
|
|
496
|
-
`;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?``:` ${
|
|
490
|
+
`)){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 Kne=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:d7(t.stdout,u7(n.stdout)),status:Gne(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),!qne(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 qne(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 Jne(e){return`ccb`+oe(`sha256`).update(e).digest(`hex`).slice(0,12)}const Yne=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function f7(e){if(e===void 0)return`terminal`;let t=U.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case H.STANDARD:{let e=t.number===void 0?void 0:Yne[t.number];if(e!==void 0)return e;break}case H.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case H.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case H.DEFAULT:case H.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const Xne={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 Zne(e){return e.replaceAll(`#`,`##`)}function Qne({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=Xne[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${f7(e)}`,`bg=${f7(t)}`,...r].join(`,`)}]`}function $ne(e){let t={},n=e=>{let n=Qne(e)+Zne(e.text);if(e.link===void 0)return n;let r=Jne(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>UP(e).map(n).join(``)),links:t}}function p7(e){return zP($ne,e)}const m7=rx.tmuxStatus.rows,h7=`@cc-candybar-status-prior`,g7=`@cc-candybar-status-wrote`,_7=`@cc-candybar-binding-prior`,v7=`@cc-candybar-renderer`,y7=[`-T`,`root`,`MouseDown1Status`],b7=Array.from({length:m7},(e,t)=>t),x7=e=>`@cc-candybar-row-${e}`,ere=e=>`#[fill=terminal]#{${x7(e)}}`,S7=e=>`status-format[${e}]`;function tre(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 nre(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 rre(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(`
|
|
491
|
+
`).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 ire=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...M7(e),...b7.map(e=>j7(S7(e))),A7(e,h7),A7(e,g7)];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:`${h7} 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`}}const I7=(e,t)=>[`set-option`,`-t`,e,v7,t];function are(e,t,n,r){let[i=``,...a]=t,o=N7(a.slice(0,2+m7)),s=a.slice(2+m7,2+2*m7),[c=``,l=``]=a.slice(2+2*m7);if(c!==``){let t=F7(c,l,n);return t.kind===`theirs`?t:{...t,commands:[I7(e,r)]}}let u=C7(i),d={};for(let e=0;e<u;e++){let t=o.formats===null?s[e]:o.formats[e];t!==void 0&&t!==``&&(d[e]=t)}let f={...d,...Object.fromEntries(Array.from({length:m7-u},(e,t)=>[u+t,ere(t)]))},p={owner:n,base:u,status:o.status,formats:o.formats,wrote:f};return{kind:`lay-out`,prior:p,commands:[[`set-option`,`-t`,e,h7,JSON.stringify(p)],I7(e,r),...P7(e,f)]}}const L7=e=>[...M7(e),A7(e,g7)];function R7(e,t,n){let r=N7(n.slice(0,2+m7)),i=n[2+m7]??``,a=[],o=[];if(nre(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,h7],[`set-option`,`-q`,`-u`,`-t`,e,g7],[`set-option`,`-q`,`-u`,`-t`,e,v7]),{commands:a,kept:o}}const ore=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,z7=[[`list-keys`,`-T`,`root`]];function B7(e){let t=ore.exec(e);return t===null?null:{line:t[0],command:t[1]}}const V7=`cc-candybar://tmux-status-click/`,sre=e=>`${V7}${Sa([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,H7=e=>e?.command.includes(V7)??!1;function U7(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,_7]};return H7(B7(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 cre=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=p7(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,L7(r));if(a===null)continue;let o=R7(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,z7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=lre(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,m7-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#{${h7}}\t#{${g7}}`]);if(n.kind===`ok`){let r=[];for(let i of n.stdout.split(`
|
|
492
|
+
`)){let[n,a,o=``]=i.split(` `);if(n===void 0||a===void 0||a===``)continue;let s=F7(a,o,this.deps.owner);s.kind===`ours`?(t.layouts.set(n,{prior:s.prior,rows:[],status:s.status}),r.push(I7(n,this.deps.name))):this.leave(e,t,n,s.why)}await this.write(e,r)}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)} ${_7} 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,ire(n));if(r===null||this.closed)return null;let i=are(n,r,this.deps.owner,this.deps.name);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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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=tre(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,g7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,rre(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`,...y7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${E7(`${this.deps.handler} ${sre(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,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 lre(e){try{return Ca(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),ure={"--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`)},dre={resume:`--resume`,fresh:`--session-id`};function fre(e){return[dre[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&&pre(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const pre=(e,t)=>e===t||e.startsWith(t+T.sep);function mre(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=ure[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`?hre(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(T.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(T.sep),repo:t.slice(0,n-1).join(T.sep)||T.sep}}function hre(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,gre=T.join(`bin`,`cc-candybar-native`),_re=CI(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=SQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const vre={band:{on:async(e,t,n)=>{let r=rn(t.bundle);if(r===null)throw new Z(`${rx.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=T.join(r,gre);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:yre(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=Wt(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${rx.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:Sre(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=SQ(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 yre(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=SQ(e.hints.tmux),a=i.kind===`refused`?i:await CQ(n.claudeInput,i.hint,_re);if(a.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${a.reason} — or type /reload-plugins yourself`);return`installed ${J7} from ${t} and typed /reload-plugins into ${a.pane}`}const bre=new Set([Xo,vP]);function xre(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Sre(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,Gt(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}) — ${rx.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=Dre(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${rx.statusline.label} off and on again`);let s=Cre(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=mre(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=xre(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])=>bre.has(e)),m=(e,t)=>Jt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...fre(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=wre(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}\`, ${Tre[g.kind](e.sessionId)}, and its statusline follows lane B`}function Cre(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 wre(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Tre={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Ere={"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 Dre(e){let t=_Q(e);return t.kind===`ready`?bQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:vQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Ere[t.kind]}var Ore=class{owed=new Map;setups=new x8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=ix.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}`),Sc(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await vre[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 kre=[`request`,`feed`],Z7=new WeakMap;let Are=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Are++;return Z7.set(e,n),n};var jre=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 kre){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 Mre=class{queue=new x8;sessions=new x8;gathers=new x8;effects=new x8;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 PQ(e);let a=this.deps.monotonic();t(Ie(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 PQ(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--}}performing(e,t){return this.effects.run(e??`clickless`,t)}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 NQ(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},Nre=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)?Vee(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 Pre(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=Dn(c),u=()=>He(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new a4(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 y1(_.session),y=new E1(v,p,_.history),b=Gr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),S=new x4,C=new zte,ee=e.doctorStores,w=new gj({clock:i,counters:m,logger:p}),te=new Ij(p),ne=new nl({watchers:w,logger:p,clock:i}),T=new tM({launcher:h,clock:i,logger:p,ledger:te,watchers:w,fileEvents:ne}),re=bne({launcher:h,host:c,watchers:w,fileEvents:ne,clock:i,logger:p,ledger:te}),{gitProvider:E,usageStore:D,tmuxService:ie,hostService:O,managedStorage:ae}=re,oe=new Bne,se=new fte,ce=new Nre({clock:i,now:u,close:async(e,t)=>{await n6({kind:`menu-idle`,session:e,idle:t},we)},failed:(e,t)=>p(t instanceof NQ?`info`:`error`,`menu-idle: close failed (session=${e}): ${x(t)}`)}),le=e.linkSigner,ue=new Ac({supersede:(e,t)=>ae.supersede(e,t),launch:h.launch,state:v,log:p,now:u,clock:i}),de=new Ore({edge:e.laneEdge(h,e=>pe.following(e),d.signal,g),host:{bundle:t.path,node:t.node,socket:o.socket,preload:As(t.path,c)},state:v,log:p,now:u,defer:e=>void i.defer(e)}),fe=new cre({edge:{run:(e,t,n)=>bc(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=${Ht(o.socket)}`,...[...t.node,t.path].map(Ht),`url-handle`].join(` `),owner:o.socket,name:`main`,log:p}),pe=new BZ({render:(e,t,n)=>ZZ(we,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>v.revision(e),t),lanes:e=>$Z(we,e),pin:e=>{let t=ve.pin(e);return()=>{ve.stopDrawing(e,`feed`),t()}},shown:e=>me.shown(e.hints.tmux),watching:()=>me.follow(),refreshes:()=>te.totals(),periods:PZ,clock:i,instant:u,log:p}),me=new Kne({clock:i,listPanes:e=>bc(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,c7]),listClients:e=>bc(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,l7]),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 jre,_e=j8(),ve=new Rne({clock:i,runs:T,stateDir:o.state,locations:l,sessionState:v,watchers:w,log:p,storage:ae,signer:le,gates:s,declare:(e,t,n,r)=>cZ(re,e,t,n,r),source:Wne({providers:re,sessionState:v,update:()=>_e.get(),history:e=>y.depth(e),navigation:(e,t)=>oe.depth(e,v,s.state.gateFor(t))})},{budgetBytes:()=>Cne(n),observers:{onReload:(e,t,n,r)=>{p(`info`,Dne(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`)}});ne.subscribe(e=>{switch(e.kind){case`period`:w.judge();return;case`caught-up`:ve.reloadEvery({kind:`events-resumed`,since:e.since}),pe.wakeWhere(`data`,()=>!0);return;case`moved`:pe.wakeWhere(`data`,()=>!0);return}});let ye=60*1e3,be=P8({clock:i,targets:t.targets,intervalMs:ye,stat:e.stat,held:()=>xe.running(),exit:()=>a(0),log:p}),xe=A8({fact:_e,clock:i,launcher:h,probe:g,entryUrl:t.entryUrl,digest:t.digest,actsDir:r8(o.state,t.path),intervalMs:ye,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>be.checkNow(),log:p}),Se=new Mre({log:p,monotonic:()=>i.monotonic()}),Ce={gates:s,sessionState:v,stateDir:o.state,locations:l,journalTurns:Se,clickLanded:e=>ce.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>xe.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];ve.reload(...t,{kind:`doctor`});let n=ve.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:ee,probes:S,clients:C,bundle:t.path,serving:()=>b.serving(),claudeInput:e.claudeInput(h),history:y,navigation:oe,configFor:e=>ve.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>ve.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>ve.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:le,runs:ue,lanes:{of:(e,t)=>eQ(we,e,t),clicked:(e,t,n)=>uQ(we,e,t,n)},diagnosticCopy:(e,t,n)=>ve.drawnCopy(e,t,n)},we={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:ee,stats:m,handlerProbes:S,renderSightings:C,watcherRegistry:w,refreshLedger:te,fileEvents:ne,payloadProviders:re,sessionState:v,effectSessions:se,menuIdle:ce,journalTurns:Se,linkSigner:le,runs:ue,sourceRuns:T,laneSetups:de,tmuxStatusLines:fe,frameFeeds:pe,renderWarnings:ge,renderCache:ve,updateWatch:xe,limits:b,verbCtx:Ce};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),H6(we,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),U6(we,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),Ce.reloadConfig(e)},arm(){d.signal.throwIfAborted(),ne.start(o.watchProbe),be.arm(),xe.arm(),b.arm()},close(e){let t=[[`journalTurns close`,()=>Se.close()],[`tmuxStatusLines restore`,()=>fe.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>pe.close()],[`menuIdle dispose`,()=>ce.dispose()],[`updateWatch close`,()=>xe.close()],[`binaryWatch close`,()=>be.close()],[`limits disarm`,()=>b.disarm()],[`renderCache close`,()=>ve.close()],[`gitService close`,()=>E.close()],[`usageStore close`,()=>D.close()],[`tmuxService close`,()=>ie.close()],[`hostService close`,()=>O.close()],[`runs close`,()=>ue.close()],[`sourceRuns close`,()=>T.close()],[`managedStorage close`,()=>ae.close()],[`fileEvents close`,()=>ne.close()],[`watcherRegistry close`,()=>w.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 Fre(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 Ire=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;try{e=s.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return Fre(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.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(T.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(T.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 Lre(e,t,n){return{session:new Ire(e.sessionState,n,500,t),history:q1(e.settingsHistory,t)}}function e9(e,t,n){for(let r of(t??``).split(T.delimiter)){if(!T.isAbsolute(r))continue;let t=T.join(r,e);if(n(t))return t}return null}function t9(e,t){try{return s.accessSync(e,t),s.statSync(e).isFile()}catch{return!1}}function Rre(e){try{return s.realpathSync(e)}catch{return T.resolve(e)}}function zre(e,t,n){let r=e9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:T.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 n9=2e3;async function r9(e,t,n,r){let i=await bc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function i9(e,t){if(t.ok)return t.stdout;let n=Ze(t,t.stdout);throw Error(`${e} failed (${Qe(t)}${n===``?``:`: ${n}`})`)}function Bre(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 Vre=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Hre(e,t){return e.split(`
|
|
493
|
+
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return Vre.exec(r.join(` `))?.[1]===t?[n]:[]})}const Ure=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Wre(e,t,n){for(let r of l0(c0(e),t)){if(r.command.split(` `).some(e=>Ure.test(e)))return!0;if(r.pid===n)return!1}return!1}const Gre=[`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(`
|
|
494
|
+
`);async function Kre(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=i9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Gre,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function a9(e,t,n){return i9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function o9(e,t){let n=await bc(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 a9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function qre(e,t){let{panePid:n,cwd:r,foreground:i}=await o9(e,t),a=await a9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Kre(e,i),c=c0(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:Wre(a,i,n)}}function Jre(e,t,n,r,i){let a=e=>Re(r,e,n);return{claudeInput:OQ(e),barPanes:async t=>Hre(await r9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await r9(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 r9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void i9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Y1(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>s.existsSync(e),presence:Fz,paneClaude:t=>qre(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+n9;for(;;){let o=await o9(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 ${n9/1e3} s`);await a(100)}},launcherNode:e=>zre(e,e=>t9(e,s.constants.X_OK),Rre),onPath:(e,t)=>{let n=e9(e,t,e=>t9(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`?Bre(i.stdout):null;return a===null?(i9(`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 r9(e,t,EQ(t.pane,`cc-candybar-lane`,[]),n)}}const Yre=/^[0-9a-f]{64}$/;function s9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Xre(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>s9(e,t).toString(`hex`),verify:(t,n)=>Yre.test(n)?ue(Buffer.from(n,`hex`),s9(e,t)):!1}}function c9(e){return T.join(e,`link.key`)}function l9(e){let t,n=()=>t??=Zre(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Zre(e){let t;try{t=s.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Qre(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 Xre(t)}function Qre(e){s.mkdirSync(T.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 $re(e,t,n){return{daemonLog:t,launcher:e=>Lt(e,n),storage:t=>Lre(e,t,n),doctorStores:E2(e.state),doctorEdge:R2,claudeInput:OQ,probe:Qs,laneEdge:(e,t,r,i)=>Jre(e,t,r,n,i),linkSigner:l9(c9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>Zr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:s.statSync}}const eie=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function u9(e){if(e===void 0)return;let t=U.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===H.STANDARD&&t.number!==void 0?eie[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const tie={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 nie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=u9(t),o=u9(n),s={};for(let e of r){let t=tie[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 rie(e){return{ok:!0,band:e.rows.map(e=>UP(e).map(nie))}}function iie(e){return zP(rie,e)}const aie={band:e=>JSON.stringify(iie(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:p7(e)})};function d9(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 oie(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();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`);return}r=!0,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(tr(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),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},null,JZ)}),u=rr(r=>{let i=Qn(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{c&&(e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):d(e.sessionId,e.lane))}).catch(t=>{e.log(`error`,`handler threw: ${x(t)}`),c&&o(YZ(t),null,JZ)}).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,JZ)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=d9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(nr(aie[i](e,t))),refused:e=>t.end(tr(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 f9=`CC_CANDYBAR_PARENT_PID`;function sie(e){let t=e[f9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${f9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function cie(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 p9=null,m9=null,h9=null,g9=null;function _9(){if(g9===null)throw Error(`runDaemon has not started`);return g9}function v9(e,t){_9().log.log(e,t)}function lie(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:on(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function uie(e){let n=En(e.host);g9={world:e,paths:n,log:new gc(n.log,e.clock)},t.on(`uncaughtException`,e=>{v9(`error`,`uncaughtException: ${e.stack||e.message}`),S9(1)}),t.on(`unhandledRejection`,e=>{v9(`error`,`unhandledRejection: ${String(e)}`),S9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{v9(`info`,`received ${e}, shutting down`),S9(0)});die().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${x(e)}`),S9(1)}async function die(){let{world:e,paths:n,log:r}=_9(),{host:i}=e,a=Lr(i.env);p9=await ec(t.pid,Qs(e.launcher).startTime);let o=await oc(cc(e,p9,n.registry));if(!o.decision.allow){v9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),S9(1);return}m9=o.registryPath,s.mkdirSync(n.state,{recursive:!0}),gn(n.socket);let c=Pre({...$re(n,r,e.clock),bundle:lie(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Pz(),exit:S9});h9=c,cie({clock:e.clock,anchor:sie(i.env),probe:Qs(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,de.createServer(e=>oie(c,e)),n.socket,!1)}function b9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){v9(`error`,`server error: ${a.message}`),S9(1);return}if(i){v9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}fie(e,n,r).catch(y9)}),n.listen(r,()=>pie(e,r))}async function fie(e,n,r){let i=await Us(Ws(_n(r)),(t,n)=>$s(t,n,Qs(e.launcher)));if(i.kind===`attach-and-exit`){v9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}v9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{s.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){v9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),S9(1);return}}b9(e,n,r,!0)}function pie(e,n){let r=qs(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}hie(n);try{s.chmodSync(n,384)}catch(e){v9(`warn`,`chmod socket failed: ${e.message}`)}v9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Ir(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Ir(e.memoryLimitBytes)}MB`),oi(_9().paths.spawnBackoff),e.arm(),mie(n,r.identity)}function mie(e,n){Xs({bound:n,myPid:t.pid,readIdentity:()=>qs(e),readLease:()=>Ws(_n(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function hie(e){let n=Gs(_n(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const gie=e=>(t,n,r)=>yc(e,{socket:t},`tmux-status`,n,r);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(gie(_9().world.launcher)),Ks(_9().paths.lease,t.pid),m9!==null&&sc(m9,t.pid,ic,e=>s.unlinkSync(e)),t.exit(e))}const _ie={connectMs:200,budgetMs:500};async function vie(e,t,n){return yie(t,await bie(e,t),n.includes(`--json`))}function yie(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
495
|
+
`:xie(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${pr(t)}\n`,code:1}}function bie(e,t){return or(e,()=>({kind:`debug`,what:t}),_ie,e=>`debug`in e?e.debug:void 0)}function xie(e){switch(e.what){case`vars`:return Sie(e.vars);case`segments`:return Cie(e.segments);case`config`:return wie(e.config);default:return e}}function Sie(e){if(e.length===0)return`no variables (DSL not active)
|
|
496
|
+
`;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?``:` ${Eie(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${Tie(a.value)}${e}${o}`)}return t.join(`
|
|
497
497
|
`)+`
|
|
498
|
-
`}function
|
|
498
|
+
`}function Cie(e){if(e.length===0)return`no segments (DSL not active)
|
|
499
499
|
`;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(`
|
|
500
500
|
`)+`
|
|
501
|
-
`}function
|
|
501
|
+
`}function wie(e){return e===null?`config: DSL not active
|
|
502
502
|
`:JSON.stringify(e,null,2)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function Tie(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Eie(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Die(){let e=kie();return e===null?null:s.readFileSync(e,`utf-8`)}function Oie(){let e;try{e=Die()}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 kie(){let e=T.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=T.dirname(T.resolve(n));for(;;){let t=T.join(r,e);if(s.existsSync(t))return t;let n=T.dirname(r);if(n===r)return null;r=n}}const C9=5e3;function Aie(e,t){return{ms:t,signal:ze(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 w9({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=IX(a,o);return{drawn:Aq(n,r,i,Fie(t,a,e.at(-1)??null,s),c,a),opts:c}}const T9=`/home/tester`,E9=N4(`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:E9,version:`1.15.0`,cwd:`${T9}/code/cc-candybar/src`,transcript_path:`${T9}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${T9}/code/cc-candybar/src`,project_dir:`${T9}/code/cc-candybar`,added_dirs:[]},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:I({branch:`main`,status:`dirty`,aheadBehind:I({ahead:2,behind:1}),head:I(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:I(`abc1234`),operation:I(`rebase`),committedAt:I(n-780),stashCount:I(1),upstream:I(`origin/main`),repoName:I(`cc-candybar`),repoUrl:I(`https://github.com/promptctl/cc-candybar`),pullRequest:L}),usage:I({session:{cost:.39,calculatedCost:.39,officialCost:null,tokens:241400,tokenBreakdown:null}}),context:I({totalTokens:48487,percentage:76,contextLeftPercentage:24,maxTokens:1e6}),metrics:I({lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,nonPrompts:0,linesAdded:512,linesRemoved:88}),activity:L,tmuxSession:I(`work`),hostName:I(`tester-box`),hostUser:I(`tester`),cache:I(n+900),speed:L,autoCompact:I(4e5),sources:new Map(r.map(e=>[e,L]))},today:I({sums:jX(t,12.5,34e5),own:{}}),gathered:{git:!0,session:!0,today:!0,context:!0,metrics:!0,activity:!0,tmux:!0,hostName:!0,hostUser:!0,cache:!0,speed:!0,autocompact:!0},declaredSources:r,faults:[]}}function Fie(e,t,n,r){let i=Nie(r),a=o7(void 0,E9,Pie(e,r),{...L,at:r},r),{term:o,...s}=mZ(a,{hookData:i,hints:Mie,neededInputPaths:GX(e,t.preset),home:T9},{effective:t,configFacts:{unsaved:1,resettable:Vx(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${T9}/.config/cc-candybar/config.json5`},history:{undo:1,redo:1,sinceEdit:1},back:1});return{...s,today:yZ(a.builtins.today,r)}}function Iie(e,t){let n=cU(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function Lie(e,n,r,i=t.cwd(),a=C9){let o=[],c=_P(i,r,e.host.home)??null,l=Dn(e.host),u=rU(l,VU(un(e.host)).read(),i,i,c??void 0);o.push(...ZH(u.repos));let d=c===null?Iie(u,o):[nU(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=uU(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 db&&o.push(...e.warnings),{kind:`fatal`,layers:d,message:e instanceof db||e instanceof Error?e.message:String(e),warnings:o})}}async function Rie(e,t,n,r,i,a,o=C9){let s=t.map(e=>e.path),c=$Y(Dn(e.host),t,TX,{warned:e=>i.push(...e)},{...n,cwd:r});oX(c.dropped);let{config:l}=c,u=new WC(e.clock),d=new tM({launcher:e.launcher,clock:e.clock}),f=new fM(d,u,l.globals.default_empty_value??``,new y1);try{let t=mq(l,f,{cwd:r,signer:l9(c9(un(e.host)))});i.push(...t.loadWarnings);let n=NZ(l,()=>null,()=>!1),p=Aie(e.clock,o);return w9({layers:s,config:l,compiled:t,store:u,registry:f},n,200,a),await f.inFlight(p.signal),{settle:p,layers:s,droppedPlugins:[...c.installed.dropped,...c.layers.flatMap(e=>e.plugins.dropped)],config:l,compiled:t,store:u,registry:f,runs:d}}catch(e){throw f.dispose(),d.close(),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,settle:d}=e,{drawn:f,opts:p}=w9(e,t,n,r);for(let e of jie(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=jq(s,c,l,u,f,r,p,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:m,failures:i,advisories:a}}async function Bie(e,t,n,r,i,a,o){let s=He(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=mS(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=NZ(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 pS(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(`
|
|
504
504
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
505
|
-
`));return d}finally{c.registry.dispose(),c.runs.close()}}function D9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function
|
|
506
|
-
`))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`,`/${
|
|
507
|
-
`));let l=o.map(e=>{let n=T.basename(e),r=T.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
505
|
+
`));return d}finally{c.registry.dispose(),c.runs.close()}}function D9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function Vie(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${SP(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${HP(e.rendered)}\n`:``),stderr:D9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:D9(e.warnings)+`✗ ${SP(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 O9=`--render`,k9=`Usage: cc-candybar check [${O9}] [config-file]\n`;function Hie(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==O9);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${k9}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${k9}`}:{kind:`run`,target:n[0],render:t.includes(O9)}}async function A9(e,n){let r=Hie(e),i=t.cwd();return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:Vie(await Lie(n,Pz(),xP(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=gP(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=T.join(e,zH),r=VH(n);if(`error`in r)throw Error(`${t}: could not list ${zH}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${zH}/<name>/${nH}`);return r.folders.map(e=>T.join(n,e,nH))}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 (${Qe(a)})`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
|
|
506
|
+
`))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`,`/${zH}/`)}function Xie({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=s.mkdtempSync(T.join(e.tmp,`cc-candybar-plugin-`));try{return Yie(t,n.url,n.shown,T.join(i,`repo`)),r(T.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(T.join(e,nH),T.join(t,nH));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(T.join(t,`.install-`));try{let o=i.map(e=>{let t=T.join(a,T.basename(T.dirname(e)));s.mkdirSync(t);try{s.copyFileSync(e,T.join(t,nH))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),c=ZY(o.map(e=>iH(T.join(e,nH),`plugins`)),TX,{root:e,git:!1},r);if(c.length>0)throw Error(c.map(e=>`${n}: ${T.join(zH,T.relative(a,e.path))} would not load: ${e.reason.split(a).join(T.join(n,zH))}`).join(`
|
|
507
|
+
`));let l=o.map(e=>{let n=T.basename(e),r=T.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,T.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:T.join(e,nH),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=>sj(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,RH(Dn(t.host)),e,t.host.home));for(let{path:t,placed:r}of n)console.log(`${r} plugin ${T.basename(T.dirname(t))} → ${t} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function j9(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
508
508
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
509
|
-
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:
|
|
510
|
-
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:
|
|
511
|
-
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function
|
|
512
|
-
`;function
|
|
513
|
-
`);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
|
|
514
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?d7(e,u7(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([bc(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,c7]),bc(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,l7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:
|
|
509
|
+
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:vte(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function M9(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 N9(e,t,n){let{env:r}=e;return{termCols:M9(r.COLUMNS,n.columns),termRows:M9(r.LINES,n.rows),ssh:tae.some(e=>(r[e]??``)!==``),tmux:Gc(r),configEnv:yP(e,t),claudeConfigDir:Zo(r,t),terminalEnv:Fn(r)}}function P9(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function nae(e){let t=u4(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=P9(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:ar(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const 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 F9(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=u4(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=F9(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 I9(e,t,n){let r=u4(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=P9(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 L9=e=>Fte.includes(e.role),oae=e=>I9(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&Ite.includes(e.rateLimits),`the rate-limit windows they carried`),sae=e=>I9(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),cae=e=>I9(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&L9(e)&&rF.includes(e.frame),`what they drew and from which project`),lae=e=>I9(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&L9(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function R9(e,t,n){let r=e.doctorStores?.[t],i=F9(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=u4(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:R9(e,`marks`,Z1),clicked:R9(e,`clicked`,e0),postMortemsRead:R9(e,`postMortemsRead`,x2)}}async function z9(e){let t=await l4(e);if(t.kind!==`ok`){let e={kind:`failed`,reason:pr(t).split(`
|
|
510
|
+
`).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 dae=` (fix: click the settings menu (${vi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,fae=`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 pae({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:dae}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${fae}\n`)}function mae({host:e,launcher:t,clock:n},r){let i={clock:n,runs:new tM({launcher:t,clock:n}),locations:Dn(e),sessionState:new y1,storage:wne,signer:l9(c9(un(e))),gates:Pz(),stateDir:un(e)},a=e7(r.projectDir,r.cwd,r.target.path,i),o=a.state??t7(r.cwd,a.repos.plugins,i);return o.registry.dispose(),i.runs.close(),{layers:a.layers,error:a.error??(o.dropped.map(e=>e.message).join(`
|
|
511
|
+
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function hae(e,t,n){return n.kind===`failed`?n:T2(e,n.value.bundle,a0(t,n.value.clients).map(({client:e})=>e))}function gae(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:a0(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function _ae(e,t){return t.kind===`failed`?t:{kind:`ok`,value:a0(e,t.value).map(e=>e.transcript)}}function vae(e,t){return t.kind===`failed`?t:{kind:`ok`,value:s0(e,t.value)}}function yae(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:e4(e.sessionId,a0(e,t.value))}async function bae(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=N9({env:r,home:e.home},i,a()),u=i0(r.CLAUDE_CODE_SESSION_ID);s={...await t4(e,l,{projectDir:o0(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:xP(o,{env:r,home:e.home},i)},()=>null,c.serving,gae(u,c.rateLimits,Qo(l.claudeConfigDir,e.home)),_ae(u,c.transcripts),u,vae(u,c.frames),yae(u,c.widths,l.termCols??null),c.stores),urlHandler:await E4(t),install:hae(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=YF(s);return{stdout:c.map(pae).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function xae(){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]
|
|
512
|
+
`;function Sae(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 Cae(e,n){let r=Sae(e);return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:await bae(R2(n.launcher,e=>mae(n,e),n.host),j4(n.launcher,n),()=>z9(n),n.host.env,t.cwd(),xae,r.configFile)}function wae(e){return!e.ok&&e.code!==`RENDER_FAILED`}function Tae(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(tr(c))),s.on(`data`,rr(e=>{let t=e;wae(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 Eae(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=Tae(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=Eae(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&&Qr(e);let t=c;c=V9(c,`fault`),l(t,!0);return}}})};return u(),{close:()=>{s=!0,o?.(),a?.close()}}}function Dae(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function Oae(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=fx(i.lane);l===null&&(c(`--lane needs one of ${ix.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let u=d9(t.stdout),d=null,f=null,p=null,m={kind:`none`},h=(e,t)=>{Dae(m,e)&&t(),m=e},g=async e=>{let i=await br(r,e,o,s,{...N9(r.host,s,t.stderr),client:Ln(`frames`,n)});i.kind!==`ok`&&(c(pr(i)),j9(i).kick&&Qr(r))},_=e=>{p?.close(),p=H9(r,pn(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 kae(e){let t=e.replace(/\n+$/,``).split(`
|
|
513
|
+
`);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 Aae(e,t,n,r){let i=e.split(`
|
|
514
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?d7(e,u7(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([bc(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,c7]),bc(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,l7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:Aae(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 jae(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 Mae(e,n){try{return await Nae(e,n),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function Nae(e,n){let{pane:r}=jae(e),i=Gc(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=kae(u());e.rows!==t.stdout.rows&&!o.zoomed&&f(await bc(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,pn(n.host),e,`pane`,{frame:e=>r(j9(yr(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 xr(n,i.socket,r);e.kind===`ok`?(_(e.value),l=e.value===null?`waiting for pane ${r}'s statusline to render on ${pn(n.host)}`:`waiting for pane ${r}'s bar`):(e.kind===`transient`&&(Qr(n),d=``),l=pr(e))}g(),await Re(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 Pae=(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 Pae(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=zt(),{host:X9}=Y9;je(!!X9.env.CC_CANDYBAR_DEBUG);const Z9=e=>e.some(e=>t.argv.includes(e));function Q9(){console.log(pP);let e=As(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 ${rx.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Jt(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const $9={install:async e=>{await iee(e,J9,Y9),t.exit(0)},"install-url-handler":async()=>{Vs(J9,Y9),t.exit(0)},"url-handle":async e=>{await eee(e[0],Y9)},daemon:async()=>{uie(Y9)},"daemon-stats":async e=>{await q9(await s4(Y9,e))},frames:async()=>{await Oae(t.argv,J9,Y9)},check:async e=>{await q9(await A9(e,Y9))},lint:async e=>{await q9(await A9(e,Y9))},plugin:async e=>{t.exit(eae(e,Y9))},schema:async()=>{await q9(Oie())},doctor:async e=>{await q9(await Cae(e,Y9))},"bar-pane":async e=>{t.exit(await Mae(e,Y9))},...Object.fromEntries(F6.map(e=>[e,async t=>{await q9(await vie(Y9,e,t))}]))};async function Fae(){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(cP.help)&&(Q9(),t.exit(0)),Z9(cP.version)&&(console.log(`cc-candybar ${nn}`),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
|
|
515
515
|
|
|
516
516
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
517
517
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -527,4 +527,4 @@ Add to ~/.claude/settings.json:
|
|
|
527
527
|
Run with --help for more options.
|
|
528
528
|
|
|
529
529
|
To test output manually:
|
|
530
|
-
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=j9(await br(Y9,e,t.argv.slice(1),t.cwd(),{...N9(X9,t.cwd(),t.stderr),client:Ln(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Qr(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})}}
|
|
530
|
+
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=j9(await br(Y9,e,t.argv.slice(1),t.cwd(),{...N9(X9,t.cwd(),t.stderr),client:Ln(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Qr(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})}}Fae();export{};
|