@promptctl/cc-candybar 1.208.1 → 1.208.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +78 -78
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o from"node:os";import s,{basename as c,dirname as l,isAbsolute as u,join as d,resolve as f,sep as p}from"node:path";import m from"node:net";import h,{appendFileSync as g,closeSync as _,constants as v,existsSync as y,fstatSync as b,linkSync as x,mkdtempSync as S,openSync as C,readFileSync as w,readSync as T,rmSync as E,statSync as ee,unlinkSync as D,writeFileSync as te}from"node:fs";import{StringDecoder as O}from"node:string_decoder";import{inspect as k,parseArgs as ne,types as A}from"node:util";import{clearImmediate as re,setImmediate as ie}from"node:timers";import{spawn as ae,spawnSync as oe}from"node:child_process";import se,{createHash as ce,createHmac as le,randomBytes as ue,randomUUID as de,timingSafeEqual as fe}from"node:crypto";import pe from"node:v8";import{open as me,readFile as he,readdir as ge,stat as _e}from"node:fs/promises";import{get as ve}from"node:https";import{WriteStream as ye}from"node:tty";import{createInterface as be}from"node:readline";var xe=Object.create,Se=Object.defineProperty,Ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,De=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=we(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ee.call(e,s)&&s!==n&&Se(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ce(t,s))||r.enumerable});return e},ke=(e,t,n)=>(n=e==null?{}:xe(Te(e)),Oe(t||!e||!e.__esModule?Se(n,`default`,{value:e,enumerable:!0}):n,e));let Ae=!1;const je=()=>Ae;function Me(e){Ae=e}function Ne(e){return je()?`[DEBUG] ${e()}\n`:``}function Pe(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}function Fe(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Ie=(e,t)=>Pe(t),Le=`main`,Re=`CC_CANDYBAR_HOME`,ze=`CC_CANDYBAR_NAME`,Be=`CC_CANDYBAR_RUNTIME_DIR`,Ve=/^[a-z0-9][a-z0-9-]*$/;function He(e,t){if(!Ve.test(e))throw Error(`${t} must be lowercase letters, digits and dashes, starting with a letter or digit, got ${JSON.stringify(e)}`);if(e.length>32)throw Error(`${t} must be at most 32 characters, got ${e.length}: ${JSON.stringify(e)}`);return e}function Ue(e){let t=He(e,ze);if(t===`main`)throw Error(`${ze} may not be ${JSON.stringify(Le)}: that is the main renderer's name, which is what an unset ${Re} and ${ze} mean`);return t}function We(e){return e===`main`?Le:He(e,`a link's renderer name`)}function Ge(e){return e===`main`?`socket`:`${e}.sock`}function Ke(e,t){let n=e[t];return n&&n.length>0?n:void 0}function qe(){let e=process.getuid();return s.join(`/tmp`,`cc-candybar-${e}`)}function Je(e){let t=Ke(e.env,Be);if(t===void 0)return qe();if(!s.isAbsolute(t))throw Error(`${Be} must be an absolute path, got ${JSON.stringify(t)}`);return t}function Ye(e){let{env:t}=e,n=Ke(t,Re),r=Ke(t,ze),i=Ke(t,`CC_CANDYBAR_SOCKET`)??null,a=Je(e);if(n!==void 0&&r!==void 0){if(!s.isAbsolute(n))throw Error(`${Re} must be an absolute path, got ${JSON.stringify(n)}`);if(i!==null)throw Error(`CC_CANDYBAR_SOCKET is set beside ${Re} and ${ze}: a named renderer's socket is its name's, so unset it`);return{kind:`named`,name:Ue(r),runtime:a,root:n}}if(n!==void 0||r!==void 0){let[e,t]=n===void 0?[ze,Re]:[Re,ze];throw Error(`${e} is set without ${t}: a renderer's home is both, or neither for the main renderer`)}return{kind:`main`,name:Le,runtime:a,roots:{state:Ke(t,`XDG_STATE_HOME`)??s.join(e.home,`.local`,`state`),cache:Ke(t,`XDG_CACHE_HOME`)??s.join(e.home,`.cache`),config:Ke(t,`XDG_CONFIG_HOME`)??s.join(e.home,`.config`)},legacySocket:i}}const Xe=new Set([`ECONNREFUSED`,`ENOENT`,`ENOTSOCK`]),Ze=e=>({cause:Xe.has(e.code??``)?`unreachable`:`io_error`,message:e.message}),Qe={dial(e){let t=m.createConnection({path:e}),n=!1;return{settled:new Promise(e=>{let r=r=>{t.off(`connect`,i),n=!0,e({ok:!1,failure:Ze(r)})},i=()=>{t.off(`error`,r),n=!0,e({ok:!0,conn:t})};t.once(`error`,r),t.once(`connect`,i)}),abandon:()=>{n||(t.removeAllListeners(),t.destroy())}}}};function $e(e,t){return e+t}function et(e,t){return Math.round(t-e)}function tt(e,t){return et(t,e.monotonic())}const nt={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=ie(e);return()=>re(t)}};function rt(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 it(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 at(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function ot(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const st=e=>e.getTime()/1e3,ct=e=>Math.round(e*1e3),lt=e=>new Date(ct(e)),ut=e=>st(new Date(e.now()));function dt(e,t){return A.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!y(t)?`working directory does not exist: ${t}`:e.message:String(e)}const ft={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function pt(e,t,n){let r=ft[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 mt(e,t){return{...e.inherited,...t.envOverlay}}function ht(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 gt=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function _t(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 gt(n);let i=Math.max(n.lastIndexOf(`
|
|
3
3
|
`),n.lastIndexOf(`\r`))+1;return`${gt(n.slice(0,r).trim())} … ${gt(n.slice(i).trim())}`}function vt(e,t=``){let n=_t(e,e.stderr);return`${ht(e)}${t}${n===``?``:`: ${n}`}`}const yt=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function bt(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 xt(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function St(e,t,n){let r=Ct(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function Ct(e,t,n){if(e.scope.signal.aborted)return yt(e.scope.signal);if(n?.aborted)return yt(n);let r=pt(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:bt(t,r.minIntervalMs,r.sinceLastMs)}const wt=`\$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 Tt(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function Et(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),Tt(e,n))}const Dt=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,Ot=e=>e===`cut`?`output cut at the ${Lt}-byte bound, so the program holding it now fails its writes`:`output failed to read`,kt=`a launched program's pipe outlived its launch: `;function At(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:`${kt}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${Ot(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${kt}${n} ${Ot(t)}`})}function jt(e,t){let n=e.pipeEvent;n===null||!ot(n,t)||(e.pipeEvent={...n,answered:!0})}function Mt(e,t,n){let r=e.pipeEvent,i=r===null?`over`:at(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:Dt(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function Nt(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[wt],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,tt(n,r)),Tt(e,`did not start: ${dt(i,void 0)}`),null}t?.onEnd(`lifeline`,tt(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>Tt(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&Tt(e,null)}),i.once(`error`,t=>Et(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>Et(e,i,`exited ${n??t}`)),a.on(`error`,t=>Et(e,i,`pipe failed: ${t.message}`)),xt(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function Pt(e,t){e.liveGroups.add(t),e.lifeline??=Nt(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function Ft(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function It(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Lt=16*1024*1024,Rt=`output exceeded ${Lt} bytes`,zt=e=>`timed out after ${e/1e3} s`;function Bt(e,t,n,r){let{stats:i}=e.scope,a=new O(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?At(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(),At(e,`cut`,t);return}let d=Math.max(0,Lt-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||Vt(e,t,n,()=>u)}}}function Vt(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 Ht=()=>`closed`;function Ut(e,t){e.on(`error`,()=>{}),e.end(t)}async function j(e,t){let{stats:n,clock:r}=e.scope,i=St(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:mt(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,tt(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:dt(e,t.cwd)});return}let c=s.pid;c!==void 0&&Pt(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ee(`output-limit`),failed:e=>{d??=e.message,ee(`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=()=>ee(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&Ft(e,c),n?.onEnd(t.category,tt(r,a)),s.off(`close`,te),s.off(`error`,D),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&Vt(e,t.category,u,Ht),i())},w=e=>C(()=>i(e)),T=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),w({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},E=()=>te(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(E);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ee=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(E);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{T(t,`SIGKILL`),l.then(()=>r.defer(E))}),T(t,`SIGTERM`))},D=e=>{w({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:dt(e,t.cwd)})};s.on(`error`,D);let te=(e,n)=>{if(b!==null){w({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:zt(t.timeoutMs??0)}:b===`output-limit`?{error:Rt}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){w({ok:!0,...h(),exitCode:e});return}w({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,te),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ee(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&Ut(u,t.stdinInput)})}function Wt(e,t){let{stats:n,clock:r}=e.scope,i=St(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:mt(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,tt(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`?zt(t.timeoutMs??0):dt(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,tt(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:dt(e,t.cwd)}}}function Gt(e,t){let{stats:n,clock:r}=e.scope,i=St(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=Kt(e,t);return n?.onEnd(t.category,tt(r,a)),o}function Kt(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:mt(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:dt(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 qt=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Jt(e,t,n){let{stats:r,clock:i}=e.scope,a=St(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:mt(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,tt(i,o)),{ok:!1,reason:`spawn-error`,error:dt(e,t.cwd)}}r?.onEnd(t.category,tt(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 Yt(e){let t;try{t=w(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 M(e,t,n,r,i){let a=`${r}.${process.pid}`;try{te(a,`${qt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{x(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{E(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 Xt(e,t,n){return Qt(e,t,n).launcher}function Zt(e,t,n){let{launcher:r,state:i}=Qt(e,t,n);return{...r,launchSync:e=>Wt(i,e)}}function Qt(e,t,n){let r={clock:t,launch:e=>xt(i,j(i,e)),launchDetachedSync:e=>Gt(i,e),launchJobSync:(e,t)=>Jt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>M(n,t,e,r,i),launcherWarnings:(e,t)=>Mt(i,e,t),answeredPipeEvent:e=>jt(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&&Et(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:Dt(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>st(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()),It(i)},{once:!0}),{launcher:r,state:i}}function $t(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const en={spawn:(e,t,n)=>ae(e,t,n),spawnSync:(e,t,n)=>oe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!$t(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}}},tn=(e,t)=>Xt(e,t,en),nn=(e,t)=>Zt(e,t,en);function rn(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=nt;return{host:e,home:an(e),launcher:nn({inherited:process.env},t),clock:t,dialer:Qe}}function an(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const on=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function sn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function cn(e){return on.test(e)?e:sn(e)}function ln(e){return`${e.dir===void 0?``:`cd ${cn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${cn(t)} `).join(``)}${[e.program,...e.args].map(cn).join(` `)}`}const un=`cc-extra`;function dn(e){return s.join(s.dirname(e),un,`src`,`bun-attach.js`)}function fn(e){return s.join(s.dirname(e),`bun-graph.js`)}const pn=`attach-preload.cjs`;function mn(e){return s.join(s.dirname(e),pn)}function hn(e,t){return ln({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const gn=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function _n(e,t){return t.isSymbolicLink()?Buffer.from(h.readlinkSync(e)):h.readFileSync(e)}function vn(e,t,n=gn){return h.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=h.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?vn(e,r):[[s.relative(e,r).split(s.sep).join(`/`),_n(r,i)]]})}function yn(e){let t=se.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function bn(e){return yn(vn(e,e))}const xn=[`Cargo.toml`,`Cargo.lock`,`src`];function Sn(e){return yn(vn(e,e,e=>xn.includes(e)))}const Cn=e=>e.slice(0,7),wn=`1.208.1`;function Tn(e){let t=s.dirname(s.dirname(e));return h.existsSync(s.join(t,`src`))?t:null}function N(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:wn,digest:e}}function En(){return`6e21d6f35e2de4f4d8a13d2cd231ff73c1e2e712bd4eb2e3ee9c12476186855f`}function Dn(e){let t=JSON.parse(h.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function On(e,t){try{let n=Tn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=bn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Dn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function kn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function An(e,t){let n=kn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=An(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function jn(e,t){let{dir:n,rest:r}=An(e,t);return s.join(n,...r)}const Mn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,Nn=e=>({kind:Mn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),Pn={statSync:e=>Nn(h.statSync(e,{bigint:!0})),lstatSync:e=>Nn(h.lstatSync(e,{bigint:!0})),readlinkSync:e=>h.readlinkSync(e),realpathSync:e=>h.realpathSync.native(e),mkdirSync:e=>void h.mkdirSync(e,{recursive:!0}),opendirSync:e=>h.opendirSync(e).closeSync(),stat:async e=>Nn(await h.promises.stat(e,{bigint:!0})),readFile:e=>h.promises.readFile(e,`utf8`),writeFile:(e,t)=>h.promises.writeFile(e,t),readdir:async e=>(await h.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:Mn(e)})),unlink:e=>h.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=h.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function Fn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function In(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Ln(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function Rn(e){return Bn(e.kind===`main`?Ln(e):e.root)}const zn=e=>jn(Pn,e);function Bn(e){return{dir:e,onDisk:zn}}function Vn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function Hn(e){return s.join(qe(),Ge(e))}function Un(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function Wn(e){h.mkdirSync(e,{recursive:!0,mode:448});let t=h.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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){Wn(s.dirname(e));for(let t of[e,Kn(e)])try{if(h.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Kn(e){return`${e}.lease`}function qn(e){return Kn(Vn(e))}function Jn(e){return s.join(Fn(e),`session-state.json`)}function Yn(e){return s.join(Fn(e),`settings-history.json`)}function Xn(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function Zn(e){return s.join(Fn(e),`spawn.lock`)}function Qn(e){return s.join(Fn(e),`spawn.cooldown`)}function $n(e){return s.join(Fn(e),`spawn.backoff`)}function er(e){return s.join(Fn(e),`watch-probe`)}function tr(e){return s.join(Fn(e),`daemon.log`)}function nr(e){return s.join(Fn(e),`link-ids`)}function rr(e){return{socket:Vn(e),lease:qn(e),state:Fn(e),log:tr(e),sessionState:Jn(e),settingsHistory:Yn(e),storedRoot:Rn(e),watchProbe:er(e),spawnBackoff:$n(e),linkIds:nr(e)}}function ir(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function ar(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Ln(t),dataHome:ir(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function or(e,t){return sr(e,t).at(-1)}function sr(e,t){let{hops:n,stopped:r}=cr(e,t);if(r!==null)throw r;return n}function cr(e,t){let n=[t];try{for(let t=0;t<ur;t++){let t=lr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${ur} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function lr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const ur=40;function dr(e,t,n){let r=or(Pn,e);h.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??h.statSync(r,{throwIfNoEntry:!1})?.mode;try{let e=h.openSync(i,`w`,a);try{h.writeFileSync(e,t),h.fsyncSync(e)}finally{h.closeSync(e)}h.renameSync(i,r)}catch(e){throw h.rmSync(i,{force:!0}),e}}function fr(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const pr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function mr(e){return Object.fromEntries(pr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const hr=[`native`,`node`,`frames`];function gr(e,t){return{kind:e,bundle:t,source:null}}const _r=[`ansi`,`frame`],vr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function yr(e){let t=Or(e.termCols),n=Or(e.termRows),r=kr(e.ssh),i=Er(e.tmux),a=Tr(e.configEnv),o=Tr(e.claudeConfigDir),s=wr(e.terminalEnv),c=Br(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 br(e,t){return vr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function xr(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 Sr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Cr(e){let t=Object.keys(Sr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Sr[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
4
|
+
`),withdraw:()=>l.end()})}function Yt(e){let t;try{t=w(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 M(e,t,n,r,i){let a=`${r}.${process.pid}`;try{te(a,`${qt(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{x(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{E(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 Xt(e,t,n){return Qt(e,t,n).launcher}function Zt(e,t,n){let{launcher:r,state:i}=Qt(e,t,n);return{...r,launchSync:e=>Wt(i,e)}}function Qt(e,t,n){let r={clock:t,launch:e=>xt(i,j(i,e)),launchDetachedSync:e=>Gt(i,e),launchJobSync:(e,t)=>Jt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>M(n,t,e,r,i),launcherWarnings:(e,t)=>Mt(i,e,t),answeredPipeEvent:e=>jt(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&&Et(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:Dt(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>st(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()),It(i)},{once:!0}),{launcher:r,state:i}}function $t(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const en={spawn:(e,t,n)=>ae(e,t,n),spawnSync:(e,t,n)=>oe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!$t(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}}},tn=(e,t)=>Xt(e,t,en),nn=(e,t)=>Zt(e,t,en);function rn(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=nt;return{host:e,home:an(e),launcher:nn({inherited:process.env},t),clock:t,dialer:Qe}}function an(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const on=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function sn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function cn(e){return on.test(e)?e:sn(e)}function ln(e){return`${e.dir===void 0?``:`cd ${cn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${cn(t)} `).join(``)}${[e.program,...e.args].map(cn).join(` `)}`}const un=`cc-extra`;function dn(e){return s.join(s.dirname(e),un,`src`,`bun-attach.js`)}function fn(e){return s.join(s.dirname(e),`bun-graph.js`)}const pn=`attach-preload.cjs`;function mn(e){return s.join(s.dirname(e),pn)}function hn(e,t){return ln({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const gn=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function _n(e,t){return t.isSymbolicLink()?Buffer.from(h.readlinkSync(e)):h.readFileSync(e)}function vn(e,t,n=gn){return h.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=h.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?vn(e,r):[[s.relative(e,r).split(s.sep).join(`/`),_n(r,i)]]})}function yn(e){let t=se.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function bn(e){return yn(vn(e,e))}const xn=[`Cargo.toml`,`Cargo.lock`,`src`];function Sn(e){return yn(vn(e,e,e=>xn.includes(e)))}const Cn=e=>e.slice(0,7),wn=`1.208.2`;function Tn(e){let t=s.dirname(s.dirname(e));return h.existsSync(s.join(t,`src`))?t:null}function N(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:wn,digest:e}}function En(){return`daa977c0fce190940cda292de325f7b2a60c3c6548ba349bc67fccfc17ae46f3`}function Dn(e){let t=JSON.parse(h.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function On(e,t){try{let n=Tn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=bn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Dn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function kn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function An(e,t){let n=kn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=An(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function jn(e,t){let{dir:n,rest:r}=An(e,t);return s.join(n,...r)}const Mn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,Nn=e=>({kind:Mn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),Pn={statSync:e=>Nn(h.statSync(e,{bigint:!0})),lstatSync:e=>Nn(h.lstatSync(e,{bigint:!0})),readlinkSync:e=>h.readlinkSync(e),realpathSync:e=>h.realpathSync.native(e),mkdirSync:e=>void h.mkdirSync(e,{recursive:!0}),opendirSync:e=>h.opendirSync(e).closeSync(),stat:async e=>Nn(await h.promises.stat(e,{bigint:!0})),readFile:e=>h.promises.readFile(e,`utf8`),writeFile:(e,t)=>h.promises.writeFile(e,t),readdir:async e=>(await h.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:Mn(e)})),unlink:e=>h.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=h.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function Fn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function In(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Ln(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function Rn(e){return Bn(e.kind===`main`?Ln(e):e.root)}const zn=e=>jn(Pn,e);function Bn(e){return{dir:e,onDisk:zn}}function Vn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function Hn(e){return s.join(qe(),Ge(e))}function Un(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function Wn(e){h.mkdirSync(e,{recursive:!0,mode:448});let t=h.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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){Wn(s.dirname(e));for(let t of[e,Kn(e)])try{if(h.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Kn(e){return`${e}.lease`}function qn(e){return Kn(Vn(e))}function Jn(e){return s.join(Fn(e),`session-state.json`)}function Yn(e){return s.join(Fn(e),`settings-history.json`)}function Xn(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function Zn(e){return s.join(Fn(e),`spawn.lock`)}function Qn(e){return s.join(Fn(e),`spawn.cooldown`)}function $n(e){return s.join(Fn(e),`spawn.backoff`)}function er(e){return s.join(Fn(e),`watch-probe`)}function tr(e){return s.join(Fn(e),`daemon.log`)}function nr(e){return s.join(Fn(e),`link-ids`)}function rr(e){return{socket:Vn(e),lease:qn(e),state:Fn(e),log:tr(e),sessionState:Jn(e),settingsHistory:Yn(e),storedRoot:Rn(e),watchProbe:er(e),spawnBackoff:$n(e),linkIds:nr(e)}}function ir(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function ar(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Ln(t),dataHome:ir(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function or(e,t){return sr(e,t).at(-1)}function sr(e,t){let{hops:n,stopped:r}=cr(e,t);if(r!==null)throw r;return n}function cr(e,t){let n=[t];try{for(let t=0;t<ur;t++){let t=lr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${ur} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function lr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const ur=40;function dr(e,t,n){let r=or(Pn,e);h.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??h.statSync(r,{throwIfNoEntry:!1})?.mode;try{let e=h.openSync(i,`w`,a);try{h.writeFileSync(e,t),h.fsyncSync(e)}finally{h.closeSync(e)}h.renameSync(i,r)}catch(e){throw h.rmSync(i,{force:!0}),e}}function fr(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const pr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function mr(e){return Object.fromEntries(pr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const hr=[`native`,`node`,`frames`];function gr(e,t){return{kind:e,bundle:t,source:null}}const _r=[`ansi`,`frame`],vr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function yr(e){let t=Or(e.termCols),n=Or(e.termRows),r=kr(e.ssh),i=Er(e.tmux),a=Tr(e.configEnv),o=Tr(e.claudeConfigDir),s=wr(e.terminalEnv),c=Br(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 br(e,t){return vr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function xr(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 Sr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Cr(e){let t=Object.keys(Sr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Sr[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
5
5
|
`)}function wr(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=pr.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 Tr(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Er(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 Dr=1e4;function Or(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Dr?Dr:t}function kr(e){return typeof e==`boolean`?e:void 0}const Ar=new Set([...[],1]);function jr(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}const Mr=Math.floor((2**31-1)/1e3)-60;function Nr(e){return typeof e==`number`&&e>0&&e<=Mr?{ok:!0,seconds:e}:{ok:!1,problem:`is not a span of seconds above 0 and at most ${Mr}`}}var Pr=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},Fr=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Ir(e){return Lr(JSON.stringify(e))}function Lr(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 Pr(`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 Pr(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function zr(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 Fr(`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(Ir(t))})}function Br(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Tr(n);return hr.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function Vr(e,t,n,r){let i=await fr(e.dialer,Vn(e.home),n.connectMs,e.clock);return i.ok?Ur(i.conn,e.clock,t,n,r):Hr(i.failure)}function Hr(e){return e.cause===`timeout`?{kind:`busy`,phase:`connect`,message:new Fr(`connect`).message}:{kind:`transient`,cause:e.cause,message:e.message}}async function Ur(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await zr(e,{v:3,...o},a,t);return Kr(o.kind,s,i)}catch(e){return qr(e)}finally{e.destroy()}}function Wr(e,t){return typeof e==`string`?e:t}function Gr(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Kr(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=Wr(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Gr(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 qr(e){if(e instanceof Pr||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 Fr?{kind:`busy`,phase:e.phase,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function Jr(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 Yr(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 Xr(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 Zr={connectMs:50,budgetMs:150},Qr={connectMs:50,budgetMs:350};function $r(e){let t=e.output;return typeof t==`string`?t:void 0}function ei(e){return Kr(`render`,e,$r)}function ti(e,t,n,r,i,a=Zr){return Vr(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,$r)}function ni(e,t,n){return Vr(e,()=>({kind:`pane-session`,socket:t,pane:n}),Qr,e=>`paneSession`in e?e.paneSession:void 0)}function ri(e,t){return Vr(e,()=>({kind:`click`,url:t}),Qr,$r)}const ii=5e3;async function ai(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 oi=`/usr/bin/footprint`;function si(e,t,n){return t===`darwin`?[di(e,oi,[`-p`,String(n)]),di(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[fi(`/proc/self/smaps_rollup`),fi(`/proc/self/status`)]:[]}function ci(e,t,n){return t===`darwin`?li(n,t=>e.launch({bin:oi,args:t,timeoutMs:ii,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function li(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 ${vt(r)}`};let i=ui(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 ui(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function di(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:ii,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:vt(r)}}}}function fi(e){return{name:e,read:async()=>{try{let t=h.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 pi=`CC_CANDYBAR_RSS_LIMIT_MB`;function mi(e){let t=e[pi];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${pi} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function hi(e){return mi(e)*2}const gi=1024*1024,P=e=>Math.round(e/gi);function _i(e){return mi(e)*gi}const vi={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function yi(e,t){return e>t}function bi(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 xi=.75;function Si(e,t){return e>t*xi}function Ci(e,t,n){let{prefix:r,suffix:i}=vi[t];return s.join(e,`${r}${n}${i}`)}function wi(e){for(let t of Object.keys(vi)){let{prefix:n,suffix:r}=vi[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Ti(e){let t=e.limitBytes??1024*gi,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=bi(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Oi(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Ei(c)} > limit ${P(t)} MB (rss ${P(a)} MB, v8 heap ${P(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await ki(e.log,`memory report`,async()=>{let t=Ci(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 ki(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Ci(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await ki(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Ai(e.listArtifacts()).slice(n))for(let n of Object.values(t))await ki(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Si(i.charge.bytes,t)?`${Ei(i.charge)} approaching limit ${P(t)} MB (v8 heap ${P(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Ai(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 Ei(e){return e.kind===`charged`?`${e.measure} ${P(e.bytes)} MB`:`rss ${P(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${P(e.gap)} MB gap`} (standing in: ${e.unread})`}function Di(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Oi({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${P(e.gap)}MB`:``;return`measure=${Di(e)} charge=${P(e.bytes)}MB rss=${P(t)}MB heap=${P(n)}MB limit=${P(r)}MB${i}`}async function ki(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Ai(e){let t=new Map;for(let n of e){let e=s.basename(n),r=wi(e);if(r===null)continue;let{prefix:i,suffix:a}=vi[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(vi);return[...t].sort(([e],[t])=>yi(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function ji(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:ci(n.launcher,process.platform,process.pid),captureMemoryReport:()=>ai(si(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>h.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>pe.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=h.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>wi(e)!==null).map(e=>s.join(i,e))},removeFile:e=>h.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Mi(e,n={}){let{home:r,clock:i}=e;if(Ji(r)!==null)return;let a=n.spawn??(()=>Xi(e)),o=Gi(r,i);if(o.kind===`contended`){let e=Pi(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Ni(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Ni(r,i,a);return}try{Ni(r,i,a)}finally{qi()}}function Ni(e,t,n){Vi(e,t)&&Fi(n)}function Pi(e,t){try{let n=h.statSync(Zn(e));return t.now()-n.mtimeMs}catch{return null}}function Fi(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 Ii(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Li(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ri(e){try{let t=h.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function zi(e,n){try{h.mkdirSync(s.dirname(e),{recursive:!0}),h.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Bi(e){try{h.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function Vi(e,n){let r=Qn(e),i=$n(e),a=Ri(i),o=Ii(Hi(r,n),Li(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`),Ui(r,n),zi(i,Math.min(a+1,5)),!0)}function Hi(e,t){try{return t.now()-h.statSync(e).mtimeMs}catch{return null}}function Ui(e,n){try{h.mkdirSync(s.dirname(e),{recursive:!0}),h.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 Wi=null;function Gi(e,n){let r=Zn(e);for(let e=0;e<2;e++){try{let e=h.openSync(r,`wx`,384);try{h.writeSync(e,JSON.stringify({pid:t.pid,ts:n.now()}))}catch{}return Wi={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(!Ki(r,n))return{kind:`contended`};try{h.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function Ki(e,t){try{let n=h.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function qi(){if(!Wi)return;let{fd:e,path:t}=Wi;Wi=null;try{h.closeSync(e)}catch{}try{h.unlinkSync(t)}catch{}}function Ji(e){try{return h.mkdirSync(Fn(e),{recursive:!0}),null}catch(t){return`mkdir ${Fn(e)}: ${t.message}`}}function Yi(e,t){return[`--max-old-space-size=${hi(t)}`,e,`daemon`]}function Xi({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:Yi(i,e.env),category:`daemon-spawn`}).ok:!1}const Zi=`cc-candybar`,Qi=`CCCandybarURLHandler`,$i=e=>e.startsWith(`${Zi}://`),ea=`closed`,ta=`open`,na=`🍫`;function ra(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 ia(e,t,n,r){let i=ra(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function aa(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function oa(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function sa(e,...t){return`{{ and ${[e,...t].map(ca).join(` `)} }}`}function ca(e){return`(eq .${e.variable} "${aa(e.member)}")`}function la(e,t,n){return`{{ ${ua(e,da(t),da(n))} }}`}function ua(e,t,n){return`action "${e}" ${t} ${n}`}function da(e){return`"${aa(e)}"`}function fa(e,t){return{kind:`state`,key:e,default:t}}function pa(e,t){return{set:e,cycle:[ea,t]}}function ma(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}var ha=De(((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]/})),ga=De(((e,t)=>{let n=ha();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)}}})),_a=De(((e,t)=>{let n=ga(),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(),ee[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===`
|
|
@@ -48,33 +48,33 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
48
48
|
`,noWrap:t?.noWrap??!1}),this._tabSize=bee(t?.tabSize??8)}_reformat(e){this._format.set({...this._format.get(),...e})}get plain(){return this._text.get()}set plain(e){let t=vp(e);this._text.set(t);let n=t.length;this._spans.set(this._spans.get().map(e=>e.end>n?new Op(e.start,Math.min(e.end,n),e.style):e).filter(e=>e.start<n))}get length(){return this._text.get().length}get cellLength(){return B(il(this._text.get(),this._tabSize).text)}get hasContent(){return this._text.get().length>0}get style(){return this._format.get().style}set style(e){this._reformat({style:Cp(e)})}get justify(){return this._format.get().justify}set justify(e){this._reformat({justify:e})}get overflow(){return this._format.get().overflow}set overflow(e){this._reformat({overflow:e})}get end(){return this._format.get().end}set end(e){this._reformat({end:e})}get noWrap(){return this._format.get().noWrap}set noWrap(e){this._reformat({noWrap:e})}get spans(){return this._spans.get()}resolvedStyle(e){return Ep(e,this._format.get().style)}edgeStyle(e,t){let n=this.resolvedStyle(t);if(this._text.get().length===0)return n;let r=e===`left`?0:this._text.get().length-1,i=n;for(let e of this._spans.get())e.start<=r&&r<e.end&&(i=i.add(Ep(t,e.style)));return i}append(t,n){if(t instanceof e){if(n!==void 0)throw Error(`Style argument must not be provided when appending RichText`);let e=this._text.get().length,r=t._spans.get().map(t=>t.move(e));this._text.set(this._text.get()+t._text.get()),this._addSpan(e,this._text.get().length,t._format.get().style);for(let e of r)this._spans.push(e);return this}let r=vp(t),i=this._text.get().length;return this._text.set(this._text.get()+r),this._addSpan(i,this._text.get().length,n??``),this}contains(t){let n=t instanceof e?t._text.get():t;return this._text.get().includes(n)}at(t){let n=t<0?this._text.get().length+t:t;return this._text.get()[n]===void 0?new e(``):this.slice(n,n+1)}slice(e,t){let n=this._text.get(),r=n.length,i=e??0,a=t??r,o=i<0?Math.max(0,r+i):Math.min(i,r),s=a<0?Math.max(0,r+a):Math.min(a,r);if(o>=s)return this.blankCopy();let c=n.slice(o,s),l=this.blankCopy(c);for(let e of this._spans.get()){let t=Math.max(e.start,o)-o,n=Math.min(e.end,s)-o;t<n&&l._spans.push(new Op(t,n,e.style))}return l}_addSpan(e,t,n){let r=Cp(n);Tp(r)||this._spans.push(new Op(e,t,r))}stylize(e,t,n){let r=this._text.get().length,i=t===void 0?0:t<0?r+t:t,a=n===void 0?r:n<0?r+n:n;if(i>=a||i>=r||a<=0)return this;let o=Math.max(0,i),s=Math.min(r,a);return this._addSpan(o,s,e),this}highlightRegex(e,t){let n=this._text.get(),r=0,i=e.flags.includes(`g`)?e.flags:e.flags+`g`,a=new RegExp(e.source,i),o;for(;(o=a.exec(n))!==null;){if(o[0].length===0){a.lastIndex++;continue}if(o.groups){let e=0;for(let[t,n]of Object.entries(o.groups))if(n!==void 0){let r=o[0].indexOf(n,e);if(r>=0){let i=o.index+r;this._addSpan(i,i+n.length,t),e=r+n.length}}r++;continue}this._addSpan(o.index,o.index+o[0].length,t??``),r++}return r}highlightWords(e,t,n){let r=n?.caseSensitive!==!1,i=0;for(let n of e){if(n.length===0)continue;let e=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=r?`g`:`gi`,o=RegExp(`\\b${e}\\b`,a),s;for(;(s=o.exec(this._text.get()))!==null;)this._addSpan(s.index,s.index+s[0].length,t),i++}return i}copy(){let e=this.blankCopy(this._text.get());return e._spans.set(this._spans.get()),e}blankCopy(t){return new e(t??``,{...this._format.get(),tabSize:this._tabSize})}split(e){let t=e??`
|
|
49
49
|
`,n=this._text.get(),r=[],i=0;for(;;){let e=n.indexOf(t,i);if(e===-1){r.push(this.slice(i));break}r.push(this.slice(i,e)),i=e+t.length}return r}divide(e){if(e.length===0)return[this.copy()];let t=[],n=0;for(let r of e)t.push(this.slice(n,r)),n=r;return t.push(this.slice(n)),t}rstrip(){let e=this._text.get().replace(/\s+$/,``);return e.length<this._text.get().length&&(this.plain=e),this}pad(e,t){let n=vp(t??` `).repeat(e);return this._spans.set(this._spans.get().map(e=>e.move(n.length))),this._text.set(n+this._text.get()+n),this}expandTabs(){let e=il(this._text.get(),this._tabSize);return this._spans.set(this._spans.get().map(t=>new Op(e.offsetOf(t.start),e.offsetOf(t.end),t.style))),this._text.set(e.text),this}padLeft(e,t){let n=vp(t??` `).repeat(e);return this._spans.set(this._spans.get().map(e=>e.move(n.length))),this._text.set(n+this._text.get()),this}padRight(e,t){return this._text.set(this._text.get()+vp(t??` `).repeat(e)),this}setLength(e){return this._text.get().length<e?this._text.set(this._text.get()+` `.repeat(e-this._text.get().length)):this._text.get().length>e&&(this.plain=this._text.get().slice(0,e)),this}extendStyle(e){let t=this._text.get().length;return this._text.set(this._text.get()+` `.repeat(e)),this._spans.set(this._spans.get().map(n=>n.end===t?n.extend(e):n)),this}truncate(e,t){if(this.cellLength<=e)return this;this.expandTabs();let n=t?.mode??`right`,r=Jc(e),i=tl(vp(t?.marker??`…`),r),a=Kc(r-B(i));if(n===`right`)return this._cropRightTo(a),i&&this._text.set(this._text.get()+i),this;if(n===`left`)return this._cropLeftTo(a),i&&(this._spans.set(this._spans.get().map(e=>e.move(i.length))),this._text.set(i+this._text.get())),this;let o=Kc(Math.floor(a/2)),s=Kc(a-o),c=tl(this._text.get(),o).length,l=this._text.get().length-nl(this._text.get(),s).length,u=this._text.get().slice(0,c),d=this._text.get().slice(l),f=c,p=l,m=i.length-(p-f),h=[];for(let e of this._spans.get())e.end<=f?h.push(e):e.start>=p?h.push(e.move(m)):(e.start<f&&h.push(new Op(e.start,f,e.style)),e.end>p&&h.push(new Op(p+m,e.end+m,e.style)));return this._text.set(u+i+d),this._spans.set(h),this}_cropRightTo(e){this.plain=tl(this._text.get(),e)}_cropLeftTo(e){let t=this._text.get().length-nl(this._text.get(),e).length,n=-t;this._spans.set(this._spans.get().map(e=>{if(!(e.end<=t))return new Op(Math.max(0,e.start+n),e.end+n,e.style)}).filter(e=>e!==void 0)),this._text.set(this._text.get().slice(t))}align(e,t){let n=this.cellLength;if(n>=t)return this;this.expandTabs();let r=t-n;switch(e){case`left`:this.padRight(r);break;case`right`:this.padLeft(r);break;case`center`:{let e=Math.floor(r/2),t=r-e;this.padLeft(e),this.padRight(t);break}}return this}removeSuffix(e){return this._text.get().endsWith(e)&&(this.plain=this._text.get().slice(0,-e.length)),this}appendTokens(e){for(let[t,n]of e)this.append(t,n);return this}static assemble(t,n){let r=new e(``,{style:n?.style});for(let n of t)if(typeof n==`string`)r.append(n);else if(n instanceof e)r.append(n);else{let[e,t]=n;r.append(e,t)}return r}static styled(t,n){let r=new e(t);return r.stylize(n),r}static fromFragments(t,n){let r=new e(``,{end:n?.end??``});for(let e of t)r.append(e);return r}*render(e){let t=il(this._text.get(),this._tabSize),n=this.resolvedStyle(e),{segments:r,covered:i}=this._buildSegments(t,n,e),a=kp(r,i);r.push(G.line());let o=G.splitLines(r),s=Jc(Nf(e,this).maxWidth),c=this._format.get().overflow??e.overflow??`fold`,l=this._format.get().noWrap||(e.noWrap??!1),u=c===`ignore`?Jc(1/0):s,d=l?Jc(1/0):u,f=c===`ignore`?void 0:this._format.get().justify??e.justify,p=_f(e,`…`,`.`);for(let e=0;e<o.length;e+=1){let t=o[e],r=a[e],i=e<o.length-1,l=cp(bp(t),d,{fold:c===`fold`}),m=G.divide(t,l),h=this._justifyLines(m.map((e,t)=>({segments:[...this._fitLine(e,u,c,p)],free:e=>r(t===0?e:l[t-1]+e)})),s,n,f);for(let e=0;e<h.length;e+=1)yield*h[e],(e<h.length-1||i)&&(yield G.line())}this._format.get().end&&(yield new G(this._format.get().end))}measure(e){let t=il(this._text.get(),this._tabSize).text.split(`
|
|
50
50
|
`),n=t.reduce((e,t)=>Math.max(e,B(t)),0),r=t.flatMap(op),i=r.length>0?r.reduce((e,t)=>Math.max(e,t),0):n,a=Jc(e.maxWidth);return{minimum:Math.min(i,a),maximum:Math.min(n,a)}}_buildSegments({text:e,offsetOf:t},n,r){let i=n=>Math.max(0,Math.min(t(n),e.length)),a=new Set;for(let e of this._spans.get())a.add(i(e.start)),a.add(i(e.end));a.delete(0),a.delete(e.length);let o=[0,...[...a].sort((e,t)=>e-t),e.length],s=new Map(o.map((e,t)=>[e,t]).reverse()),c=o.slice(0,-1).map(()=>n),l=c.map(()=>!1);for(let e of this._spans.get()){let t=i(e.end),n=Ep(r,e.style),a=s.get(i(e.start));for(let e=a;o[e]<t;e++)c[e]=c[e].add(n),l[e]=!0}return{segments:c.map((t,n)=>new G(e.slice(o[n],o[n+1]),t.isNull?void 0:t)),covered:l}}_justifyLines(e,t,n,r){return r===`full`?e.map(({segments:r},i)=>i===e.length-1?r:this._fillLine(r,t,n)):e.map(e=>[...this._justifyLine(e,t,n,r)])}*_justifyLine({segments:e,free:t},n,r,i){let a=r.isNull?void 0:r;switch(i){case`center`:case`right`:{let r=G.adjustLineLength(e,G.getLineLength(e)-xp(e),void 0,!1),o=Math.max(n-G.getLineLength(r),0),s=i===`center`?Math.floor(o/2):o;yield*Ap(r,t,s,o-s,a);break}case`left`:yield*Ap(e,t,0,Math.max(n-G.getLineLength(e),0),a);break;default:yield*e;break}}_fillLine(e,t,n){let r=bp(e),i=r.split(` `);r.endsWith(` `)&&i.pop();let a=i.length-1,o=Array(a).fill(1),s=i.reduce((e,t)=>e+B(t),0)+a;for(let e=0;s<t&&a>0;e=(e+1)%a)o[a-1-e]+=1,s+=1;let c=[],l=0;for(let e=0;e<i.length;e+=1)l+=B(i[e]),c.push(l),l+=1,e<a&&c.push(l);let u=G.divide(e,c),d=(e,t)=>e.filter(e=>e.hasText).at(t)?.style??n,f=[];for(let e=0;e<i.length;e+=1)if(f.push(...u[e*2]),e<a){let t=d(u[e*2],-1),r=d(u[e*2+2],0),i=t.equals(r)?t:n;f.push(new G(` `.repeat(o[e]),i.isNull?void 0:i))}return f}*_fitLine(e,t,n,r){let i=G.getLineLength(e);if(i-xp(e)<=t){yield*G.adjustLineLength(e,Math.min(i,t),void 0,!1);return}if(n===`ellipsis`&&t>0){yield*G.adjustLineLength(e,t-1,void 0,!1),yield new G(r);return}yield*G.adjustLineLength(e,t,void 0,!1)}};function kp(e,t){let n=[[]];return e.forEach((e,r)=>{e.text.split(`
|
|
51
|
-
`).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+B(e),free:!t[r]})})}),n.map(e=>t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].end<=t?n=i+1:r=i}return e[n].free})}function*Ap(e,t,n,r,i){if(n+r===0)return yield*e;let a=e.filter(e=>e.text!==``),o=e=>` `.repeat(e),s=G.getLineLength(a);if(s===0)return yield new G(o(n+r),i);let c=a.length-1,l=n>0&&a[0].cellLength>0&&t(0),u=r>0&&a[c].cellLength>0&&t(s-1),d=+!!l,f=u?c:c+1;if(d>f){yield new G(o(n)+a[0].text+o(r),i);return}n>0&&(yield new G(o(n)+(l?a[0].text:``),i)),yield*a.slice(d,f),r>0&&(yield new G((u?a[c].text:``)+o(r),i))}const jp=Object.freeze({name:`join`});function Mp(e,t,n,r){let i=e.join(t,n,r);return{render:e=>G.anchorLines([[...kf(i,e)]],jp)[0]}}function Np(e){return{render:t=>G.anchorLines([[...kf(e,t)]],e)[0]}}var Pp=class{items;joiner;constructor(e,t){this.items=e,this.joiner=t}*render(e){let t=this.items;if(t.length===0)return;let n={...e,justify:void 0};yield*kf(Mp(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*kf(Np(r),n);let i=e+1<t.length?t[e+1]:null;yield*kf(Mp(this.joiner,r,i,{index:e+1}),n)}yield G.line()}measure(e){let t=0;for(let n of kf(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const Fp=[`seam`,`lead`,`tail`];function*Ip(e){yield e,`mix`in e&&(yield*Ip(e.mix[0]),yield*Ip(e.mix[1]))}const Lp=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,Rp=(e,t,n,r)=>{let i=Lp(e);return i[Math.floor(parseInt(up(`${t}:${n}:${r}`),16)/2**32*i.length)]},zp=e=>B(Lp(e)[0]??``);function Bp(e,t,n){if(e===`ground`)return n(`mixes ground, whose colour is unknown`);let r=typeof e==`object`&&e?e:{};if((r.edge===`left`||r.edge===`right`)&&(r.part===`bg`||r.part===`fg`))return r.edge===t&&n(`names the ${t} neighbour, which this part is drawn without`),Object.freeze({edge:r.edge,part:r.part});if(typeof r.role==`string`)return Object.freeze({role:r.role});if(Array.isArray(r.mix)&&r.mix.length===3){let[e,i,a]=r.mix;return(typeof a!=`number`||!(a>=0&&a<=1))&&n(`mixes at ${String(a)}, outside 0..1`),Object.freeze({mix:Object.freeze([Bp(e,t,n),Bp(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const Vp=(e,t,n)=>e===`ground`?e:Bp(e,t,n),Hp={seam:void 0,lead:`left`,tail:`right`},Up={seam:`seam`,lead:`caps`,tail:`caps`};function Wp(e,t,n,r){let i=e.glyph,a=typeof i==`object`&&i?i.oneOf:void 0;typeof i!=`string`&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))&&r(`has a glyph that is neither a string nor a oneOf of strings: ${JSON.stringify(i)}`),e.fg===`ground`&&e.bg===`ground`&&r(`has ground on both sides`);let o=Lp(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>B(t)!==zp(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(gf)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:Vp(e.fg,Hp[n],r),bg:Vp(e.bg,Hp[n],r)})}function Gp(e,t,n,r){let i=e,a=Up[n];if(typeof i?.[t]!=`object`||i[t]===null)throw Error(`${a}: has no ${t} form`);let o=i[t][n];if(!Array.isArray(o))throw Error(`${a}: ${t} ${n} is not a list of cells`);return Object.freeze(o.map((e,i)=>{let o=e=>{throw Error(`${a}: ${t} ${n}[${i}] ${e}`)};return typeof e==`object`&&e?r(e,o):o(`is not a cell`)}))}const Kp=(e,t)=>(n,r)=>Wp(n,e,t,r),qp=(e,t)=>(n,r)=>{if(!(`cap`in n))return Wp(n,e,t,r);let{cap:i}=n;return Object.keys(n).length!==1&&r(`names a cap and draws cells of its own; a cell is one or the other`),i===`lead`||i===`tail`?Object.freeze({cap:i}):r(`names a cap that is neither lead nor tail: ${JSON.stringify(i)}`)};function Jp(e){let t=t=>Object.freeze({seam:Gp(e,t,`seam`,qp(t,`seam`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Yp(e){let t=t=>Object.freeze({lead:Gp(e,t,`lead`,Kp(t,`lead`)),tail:Gp(e,t,`tail`,Kp(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Xp(e,t){return{seam:e.seam.flatMap(e=>`cap`in e?t[e.cap]:[e]),lead:t.lead,tail:t.tail}}const Zp=(e,t)=>new Set([e.fg,e.bg].flatMap(e=>e===`ground`?[]:[...Ip(e)].flatMap(e=>`edge`in e&&e.edge===t?[e.part]:[]))),Qp=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...Ip(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function $p(e){let t=t=>e[t].map(e=>({cell:e,parts:{left:Zp(e,`left`),right:Zp(e,`right`)}}));return{shape:e,reads:{seam:{left:Qp(e.seam,`left`),right:Qp(e.seam,`right`)},lead:Qp(e.lead,`right`),tail:Qp(e.tail,`left`)},cells:{seam:t(`seam`),lead:t(`lead`),tail:t(`tail`)}}}function em(e){return e!==void 0&&!e.isDefault?e:void 0}function tm(e){return e.flattenAlpha(cl)}function nm(e,t){if(e.isDefault||t.isDefault)return!0;let[n,r]=[e.fixedValue,t.fixedValue];return n!==void 0&&r!==void 0?bu.fromRgba(n).deltaE(bu.fromRgba(r))>=.04:e.number===void 0?e.name!==t.name:e.number!==t.number}const rm=.001;function*im(e){for(let t=1;t*rm<=1;t++)for(let n of[e.l+t*rm,e.l-t*rm])n>=0&&n<=1&&(yield new bu(n,e.c,e.h))}function am(e,t,n){if(e===void 0||t===void 0)return e;let r=(e,n)=>new W({color:e,bgcolor:t}).drawnColors(n),{color:i,bgcolor:a}=r(e,n);if(nm(i,a))return e;let o=r(e).color,s=i.fixedValue===void 0?H.STANDARD:H.TRUECOLOR;for(let e of im(bu.fromRgba(o.getTruecolor()))){let t=r(U.fromRgba(e.toRgba()).downgrade(s),n).color;if(nm(t,a))return t}throw Error(`no colour on the lightness ray of ${e.name} stands off ${t.name} at depth ${H[n]}`)}function om(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=em(n?.bgcolor);return r&&tm(r)}if(`role`in e)return vf(n,e.role).color;let[r,i,a]=e.mix,o=om(r,t,n),s=om(i,t,n);return o&&s&&U.blend(o,s,a)}function sm(e,t,n){if(e.fg===`ground`)return new W({color:e.bg===`ground`?void 0:om(e.bg,t,n),reverse:!0});let r=e.bg===`ground`?void 0:om(e.bg,t,n);return new W({color:am(om(e.fg,t,n),r,n.colorSystem??H.TRUECOLOR),bgcolor:r})}var cm=class e{cell;parts;neighbours;edges;options;reads;follows;style;constructor(e,t,n,r,i){this.cell=e,this.parts=t,this.neighbours=n,this.edges=r,this.options=i;let a=e=>{if(t[e].size===0)return null;let[i,a]=[n[e],r[e]];if(i===null||a===void 0)throw Error(`a join cell paints with its ${e} neighbour's edge, and the join has no ${e} neighbour`);return{owner:i,edge:a}};this.reads={left:a(`left`),right:a(`right`)},this.follows=this.reads.left!==null||this.reads.right!==null,this.style=sm(e,r,i)}rederived(t,n,r){let i=e=>t[e]?.color!==void 0&&this.parts[e].has(`fg`)||t[e]?.bgcolor!==void 0&&this.parts[e].has(`bg`);if(!i(`left`)&&!i(`right`))return;let a=(e,t)=>t===void 0?e:new W({color:t.color??e?.color,bgcolor:t.bgcolor??e?.bgcolor}),o={left:a(this.edges.left,t.left),right:a(this.edges.right,t.right)},s=new e(this.cell,this.parts,this.neighbours,o,{...this.options,colorSystem:r}),c=e=>({...e,owner:e.owner===this?s:e.owner,inner:e.inner&&c(e.inner)});return{colors:s.style,style:n.withAnchor(n.anchor&&c(n.anchor))}}};function lm(e){for(let t=e;t;t=t.inner)if(t.owner instanceof cm)return t.owner}const um=e=>Fp.flatMap(t=>e[t].flatMap(Lp)).join(``);var dm=class{seam;caps;_forms;constructor(e,t){this.seam=Jp(e),this.caps=Yp(t),this._forms={glyph:$p(Xp(this.seam.glyph,this.caps.glyph)),ascii:$p(Xp(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{cells:a,reads:o}=_f(i,r.glyph,r.ascii,e=>um(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=em(s.left?.bgcolor),l=em(s.right?.bgcolor),u=e!==null&&(!o.seam.left||c!==void 0),d=t!==null&&(!o.seam.right||l!==void 0),f=d&&(!o.lead||l!==void 0),p=u&&(!o.tail||c!==void 0),m={left:e,right:t},h=e=>a[e].map(({cell:t,parts:r},a)=>{let o=new cm(t,r,m,s,i);return new G(Rp(t,e,n,a),o.style.withAnchor({owner:o,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*h(f?`lead`:`tail`));return}yield*h(`seam`)}}}};const fm={edge:`left`,part:`bg`},pm={edge:`right`,part:`bg`},mm={edge:`left`,part:`fg`},hm={mix:[fm,pm,1/2]},gm=`ground`,_m={cap:`lead`},vm={cap:`tail`},ym=(e,t)=>({glyph:e,ascii:t}),bm={glyph:``,ascii:`>`},xm={glyph:``,ascii:`/`},Sm={glyph:``,ascii:`\\`},Cm={glyph:``,ascii:`}`},wm={glyph:``,ascii:`#`},Tm={glyph:``,ascii:`]`},Em={glyph:``,ascii:`)`},Dm=e=>({seam:[{glyph:e,fg:fm,bg:pm}]}),Om=e=>ym(Dm(e.glyph),Dm(e.ascii));function km(e){let t=e=>({mix:[fm,pm,e]});return{seam:[{glyph:e,fg:fm,bg:t(1/3)},{glyph:e,fg:t(1/3),bg:t(2/3)},{glyph:e,fg:t(2/3),bg:pm}]}}const Am=e=>({seam:[vm,...e,_m]}),jm=(e,t)=>({seam:[{glyph:e,fg:t,bg:hm}]}),Mm=e=>jm({oneOf:e},fm),Nm={seam:[{glyph:` | `,fg:{role:`strip.separator`},bg:gm}]},Pm={glyph:` `,fg:mm,bg:gm},Fm=e=>({glyph:e,fg:{role:`strip.rail`},bg:gm}),Im=Object.freeze({powerline:Jp(Om(bm)),prism:Jp(ym(km(bm.glyph),km(bm.ascii))),slant:Jp(Om(xm)),backslant:Jp(Om(Sm)),flame:Jp(Om(Cm)),pixel:Jp(Om(wm)),ice:Jp(Om(Tm)),bubble:Jp(Om(Em)),capsule:Jp(ym(Am([Pm]),Am([Pm]))),wrapper:Jp(ym(Am([]),Am([]))),metro:Jp(ym(Am([Fm(`──`)]),Am([Fm(`--`)]))),stitch:Jp(ym(jm(`┊`,mm),jm(`:`,mm))),torn:Jp(ym(Mm([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),Mm([`/\\`,`\\/`]))),plain:Jp(ym(Nm,Nm))}),Lm=e=>ym({lead:[{glyph:e.glyph,fg:gm,bg:pm}],tail:[{glyph:e.glyph,fg:fm,bg:gm}]},{lead:[],tail:[{glyph:e.ascii,fg:fm,bg:gm}]}),Rm=(e,t)=>({lead:[{glyph:e,fg:pm,bg:gm}],tail:[{glyph:t,fg:fm,bg:gm}]}),zm={lead:[],tail:[]},Bm=Object.freeze({powerline:Yp(Lm(bm)),slant:Yp(Lm(xm)),backslant:Yp(Lm(Sm)),flame:Yp(Lm(Cm)),pixel:Yp(Lm(wm)),ice:Yp(Lm(Tm)),bubble:Yp(Lm(Em)),capsule:Yp(ym(Rm(``,``),Rm(`(`,`)`))),wrapper:Yp(ym(Rm(``,``),Rm(`<`,`>`))),flat:Yp(ym(zm,zm))}),Vm=Object.freeze({powerline:new dm(Im.powerline,Bm.powerline),prism:new dm(Im.prism,Bm.powerline),slant:new dm(Im.slant,Bm.slant),backslant:new dm(Im.backslant,Bm.backslant),flame:new dm(Im.flame,Bm.flame),pixel:new dm(Im.pixel,Bm.pixel),ice:new dm(Im.ice,Bm.ice),bubble:new dm(Im.bubble,Bm.bubble),capsule:new dm(Im.capsule,Bm.capsule),wrapper:new dm(Im.wrapper,Bm.wrapper),metro:new dm(Im.metro,Bm.capsule),stitch:new dm(Im.stitch,Bm.flat),torn:new dm(Im.torn,Bm.flat),plain:new dm(Im.plain,Bm.flat)});function Hm(e,t){let n=t.reducedMotion?e.style?.reduced():e.style;return n===e.style?e:new G(e.text,n,e.control)}function Um(e,t){if(e.isControl)return``;let{text:n,style:r}=Hm(e,t);if(n.length===0||r===void 0)return n;let i=t.colorSystem===null?``:r.toSgrCodes(t.colorSystem),a=i.length>0?`\x1b[${i}m${n}\x1b[0m`:n,o=t.hyperlinks?r.link:void 0;return o===void 0?a:`${pp(o)}${a}]8;;\\`}function Wm(e,t){let n=[];for(let r of e)n.push(Um(r,t));return n.join(``)}function Gm(e){return e.end=``,e.plain=e.plain.replaceAll(`
|
|
52
|
-
`,` `),e.expandTabs()}const
|
|
51
|
+
`).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+B(e),free:!t[r]})})}),n.map(e=>t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].end<=t?n=i+1:r=i}return e[n].free})}function*Ap(e,t,n,r,i){if(n+r===0)return yield*e;let a=e.filter(e=>e.text!==``),o=e=>` `.repeat(e),s=G.getLineLength(a);if(s===0)return yield new G(o(n+r),i);let c=a.length-1,l=n>0&&a[0].cellLength>0&&t(0),u=r>0&&a[c].cellLength>0&&t(s-1),d=+!!l,f=u?c:c+1;if(d>f){yield new G(o(n)+a[0].text+o(r),i);return}n>0&&(yield new G(o(n)+(l?a[0].text:``),i)),yield*a.slice(d,f),r>0&&(yield new G((u?a[c].text:``)+o(r),i))}const jp=Object.freeze({name:`join`});function Mp(e,t,n,r){let i=e.join(t,n,r);return{render:e=>G.anchorLines([[...kf(i,e)]],jp)[0]}}function Np(e){return{render:t=>G.anchorLines([[...kf(e,t)]],e)[0]}}var Pp=class{items;joiner;constructor(e,t){this.items=e,this.joiner=t}*render(e){let t=this.items;if(t.length===0)return;let n={...e,justify:void 0};yield*kf(Mp(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*kf(Np(r),n);let i=e+1<t.length?t[e+1]:null;yield*kf(Mp(this.joiner,r,i,{index:e+1}),n)}yield G.line()}measure(e){let t=0;for(let n of kf(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const Fp=[`seam`,`lead`,`tail`];function*Ip(e){yield e,`mix`in e&&(yield*Ip(e.mix[0]),yield*Ip(e.mix[1]))}const Lp=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,Rp=(e,t,n,r)=>{let i=Lp(e);return i[Math.floor(parseInt(up(`${t}:${n}:${r}`),16)/2**32*i.length)]},zp=e=>B(Lp(e)[0]??``);function Bp(e,t,n){if(e===`ground`)return n(`mixes ground, whose colour is unknown`);let r=typeof e==`object`&&e?e:{};if((r.edge===`left`||r.edge===`right`)&&(r.part===`bg`||r.part===`fg`))return r.edge===t&&n(`names the ${t} neighbour, which this part is drawn without`),Object.freeze({edge:r.edge,part:r.part});if(typeof r.role==`string`)return Object.freeze({role:r.role});if(Array.isArray(r.mix)&&r.mix.length===3){let[e,i,a]=r.mix;return(typeof a!=`number`||!(a>=0&&a<=1))&&n(`mixes at ${String(a)}, outside 0..1`),Object.freeze({mix:Object.freeze([Bp(e,t,n),Bp(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const Vp=(e,t,n)=>e===`ground`?e:Bp(e,t,n),Hp={seam:void 0,lead:`left`,tail:`right`},Up={seam:`seam`,lead:`caps`,tail:`caps`};function Wp(e,t,n,r){let i=e.glyph,a=typeof i==`object`&&i?i.oneOf:void 0;typeof i!=`string`&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))&&r(`has a glyph that is neither a string nor a oneOf of strings: ${JSON.stringify(i)}`),e.fg===`ground`&&e.bg===`ground`&&r(`has ground on both sides`);let o=Lp(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>B(t)!==zp(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(gf)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:Vp(e.fg,Hp[n],r),bg:Vp(e.bg,Hp[n],r)})}function Gp(e,t,n,r){let i=e,a=Up[n];if(typeof i?.[t]!=`object`||i[t]===null)throw Error(`${a}: has no ${t} form`);let o=i[t][n];if(!Array.isArray(o))throw Error(`${a}: ${t} ${n} is not a list of cells`);return Object.freeze(o.map((e,i)=>{let o=e=>{throw Error(`${a}: ${t} ${n}[${i}] ${e}`)};return typeof e==`object`&&e?r(e,o):o(`is not a cell`)}))}const Kp=(e,t)=>(n,r)=>Wp(n,e,t,r),qp=(e,t)=>(n,r)=>{if(!(`cap`in n))return Wp(n,e,t,r);let{cap:i}=n;return Object.keys(n).length!==1&&r(`names a cap and draws cells of its own; a cell is one or the other`),i===`lead`||i===`tail`?Object.freeze({cap:i}):r(`names a cap that is neither lead nor tail: ${JSON.stringify(i)}`)};function Jp(e){let t=t=>Object.freeze({seam:Gp(e,t,`seam`,qp(t,`seam`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Yp(e){let t=t=>Object.freeze({lead:Gp(e,t,`lead`,Kp(t,`lead`)),tail:Gp(e,t,`tail`,Kp(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Xp(e,t){return{seam:e.seam.flatMap(e=>`cap`in e?t[e.cap]:[e]),lead:t.lead,tail:t.tail}}const Zp=(e,t)=>new Set([e.fg,e.bg].flatMap(e=>e===`ground`?[]:[...Ip(e)].flatMap(e=>`edge`in e&&e.edge===t?[e.part]:[]))),Qp=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...Ip(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function $p(e){let t=t=>e[t].map(e=>({cell:e,parts:{left:Zp(e,`left`),right:Zp(e,`right`)}}));return{shape:e,reads:{seam:{left:Qp(e.seam,`left`),right:Qp(e.seam,`right`)},lead:Qp(e.lead,`right`),tail:Qp(e.tail,`left`)},cells:{seam:t(`seam`),lead:t(`lead`),tail:t(`tail`)}}}function em(e){return e!==void 0&&!e.isDefault?e:void 0}function tm(e){return e.flattenAlpha(cl)}function nm(e,t){if(e.isDefault||t.isDefault)return!0;let[n,r]=[e.fixedValue,t.fixedValue];return n!==void 0&&r!==void 0?bu.fromRgba(n).deltaE(bu.fromRgba(r))>=.04:e.number===void 0?e.name!==t.name:e.number!==t.number}const rm=.001;function*im(e){for(let t=1;t*rm<=1;t++)for(let n of[e.l+t*rm,e.l-t*rm])n>=0&&n<=1&&(yield new bu(n,e.c,e.h))}function am(e,t,n){if(e===void 0||t===void 0)return e;let r=(e,n)=>new W({color:e,bgcolor:t}).drawnColors(n),{color:i,bgcolor:a}=r(e,n);if(nm(i,a))return e;let o=r(e).color,s=i.fixedValue===void 0?H.STANDARD:H.TRUECOLOR;for(let e of im(bu.fromRgba(o.getTruecolor()))){let t=r(U.fromRgba(e.toRgba()).downgrade(s),n).color;if(nm(t,a))return t}throw Error(`no colour on the lightness ray of ${e.name} stands off ${t.name} at depth ${H[n]}`)}function om(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=em(n?.bgcolor);return r&&tm(r)}if(`role`in e)return vf(n,e.role).color;let[r,i,a]=e.mix,o=om(r,t,n),s=om(i,t,n);return o&&s&&U.blend(o,s,a)}function sm(e,t,n){if(e.fg===`ground`)return new W({color:e.bg===`ground`?void 0:om(e.bg,t,n),reverse:!0});let r=e.bg===`ground`?void 0:om(e.bg,t,n);return new W({color:am(om(e.fg,t,n),r,n.colorSystem??H.TRUECOLOR),bgcolor:r})}var cm=class e{cell;parts;neighbours;edges;options;reads;follows;style;constructor(e,t,n,r,i){this.cell=e,this.parts=t,this.neighbours=n,this.edges=r,this.options=i;let a=e=>{if(t[e].size===0)return null;let[i,a]=[n[e],r[e]];if(i===null||a===void 0)throw Error(`a join cell paints with its ${e} neighbour's edge, and the join has no ${e} neighbour`);return{owner:i,edge:a}};this.reads={left:a(`left`),right:a(`right`)},this.follows=this.reads.left!==null||this.reads.right!==null,this.style=sm(e,r,i)}rederived(t,n,r){let i=e=>t[e]?.color!==void 0&&this.parts[e].has(`fg`)||t[e]?.bgcolor!==void 0&&this.parts[e].has(`bg`);if(!i(`left`)&&!i(`right`))return;let a=(e,t)=>t===void 0?e:new W({color:t.color??e?.color,bgcolor:t.bgcolor??e?.bgcolor}),o={left:a(this.edges.left,t.left),right:a(this.edges.right,t.right)},s=new e(this.cell,this.parts,this.neighbours,o,{...this.options,colorSystem:r}),c=e=>({...e,owner:e.owner===this?s:e.owner,inner:e.inner&&c(e.inner)});return{colors:s.style,style:n.withAnchor(n.anchor&&c(n.anchor))}}};function lm(e){for(let t=e;t;t=t.inner)if(t.owner instanceof cm)return t.owner}const um=e=>Fp.flatMap(t=>e[t].flatMap(Lp)).join(``);var dm=class{seam;caps;_forms;constructor(e,t){this.seam=Jp(e),this.caps=Yp(t),this._forms={glyph:$p(Xp(this.seam.glyph,this.caps.glyph)),ascii:$p(Xp(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{cells:a,reads:o}=_f(i,r.glyph,r.ascii,e=>um(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=em(s.left?.bgcolor),l=em(s.right?.bgcolor),u=e!==null&&(!o.seam.left||c!==void 0),d=t!==null&&(!o.seam.right||l!==void 0),f=d&&(!o.lead||l!==void 0),p=u&&(!o.tail||c!==void 0),m={left:e,right:t},h=e=>a[e].map(({cell:t,parts:r},a)=>{let o=new cm(t,r,m,s,i);return new G(Rp(t,e,n,a),o.style.withAnchor({owner:o,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*h(f?`lead`:`tail`));return}yield*h(`seam`)}}}};const fm={edge:`left`,part:`bg`},pm={edge:`right`,part:`bg`},mm={edge:`left`,part:`fg`},hm={mix:[fm,pm,1/2]},gm=`ground`,_m={cap:`lead`},vm={cap:`tail`},ym=(e,t)=>({glyph:e,ascii:t}),bm={glyph:``,ascii:`>`},xm={glyph:``,ascii:`/`},Sm={glyph:``,ascii:`\\`},Cm={glyph:``,ascii:`}`},wm={glyph:``,ascii:`#`},Tm={glyph:``,ascii:`]`},Em={glyph:``,ascii:`)`},Dm=e=>({seam:[{glyph:e,fg:fm,bg:pm}]}),Om=e=>ym(Dm(e.glyph),Dm(e.ascii));function km(e){let t=e=>({mix:[fm,pm,e]});return{seam:[{glyph:e,fg:fm,bg:t(1/3)},{glyph:e,fg:t(1/3),bg:t(2/3)},{glyph:e,fg:t(2/3),bg:pm}]}}const Am=e=>({seam:[vm,...e,_m]}),jm=(e,t)=>({seam:[{glyph:e,fg:t,bg:hm}]}),Mm=e=>jm({oneOf:e},fm),Nm={seam:[{glyph:` | `,fg:{role:`strip.separator`},bg:gm}]},Pm={glyph:` `,fg:mm,bg:gm},Fm=e=>({glyph:e,fg:{role:`strip.rail`},bg:gm}),Im=Object.freeze({powerline:Jp(Om(bm)),prism:Jp(ym(km(bm.glyph),km(bm.ascii))),slant:Jp(Om(xm)),backslant:Jp(Om(Sm)),flame:Jp(Om(Cm)),pixel:Jp(Om(wm)),ice:Jp(Om(Tm)),bubble:Jp(Om(Em)),capsule:Jp(ym(Am([Pm]),Am([Pm]))),wrapper:Jp(ym(Am([]),Am([]))),metro:Jp(ym(Am([Fm(`──`)]),Am([Fm(`--`)]))),stitch:Jp(ym(jm(`┊`,mm),jm(`:`,mm))),torn:Jp(ym(Mm([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),Mm([`/\\`,`\\/`]))),plain:Jp(ym(Nm,Nm))}),Lm=e=>ym({lead:[{glyph:e.glyph,fg:gm,bg:pm}],tail:[{glyph:e.glyph,fg:fm,bg:gm}]},{lead:[],tail:[{glyph:e.ascii,fg:fm,bg:gm}]}),Rm=(e,t)=>({lead:[{glyph:e,fg:pm,bg:gm}],tail:[{glyph:t,fg:fm,bg:gm}]}),zm={lead:[],tail:[]},Bm=Object.freeze({powerline:Yp(Lm(bm)),slant:Yp(Lm(xm)),backslant:Yp(Lm(Sm)),flame:Yp(Lm(Cm)),pixel:Yp(Lm(wm)),ice:Yp(Lm(Tm)),bubble:Yp(Lm(Em)),capsule:Yp(ym(Rm(``,``),Rm(`(`,`)`))),wrapper:Yp(ym(Rm(``,``),Rm(`<`,`>`))),flat:Yp(ym(zm,zm))}),Vm=Object.freeze({powerline:new dm(Im.powerline,Bm.powerline),prism:new dm(Im.prism,Bm.powerline),slant:new dm(Im.slant,Bm.slant),backslant:new dm(Im.backslant,Bm.backslant),flame:new dm(Im.flame,Bm.flame),pixel:new dm(Im.pixel,Bm.pixel),ice:new dm(Im.ice,Bm.ice),bubble:new dm(Im.bubble,Bm.bubble),capsule:new dm(Im.capsule,Bm.capsule),wrapper:new dm(Im.wrapper,Bm.wrapper),metro:new dm(Im.metro,Bm.capsule),stitch:new dm(Im.stitch,Bm.flat),torn:new dm(Im.torn,Bm.flat),plain:new dm(Im.plain,Bm.flat)});function Hm(e,t){let n=t.reducedMotion?e.style?.reduced():e.style;return n===e.style?e:new G(e.text,n,e.control)}function Um(e,t){if(e.isControl)return``;let{text:n,style:r}=Hm(e,t);if(n.length===0||r===void 0)return n;let i=t.colorSystem===null?``:r.toSgrCodes(t.colorSystem),a=i.length>0?`\x1b[${i}m${n}\x1b[0m`:n,o=t.hyperlinks?r.link:void 0;return o===void 0?a:`${pp(o)}${a}]8;;\\`}function Wm(e,t){let n=[];for(let r of e)n.push(Um(r,t));return n.join(``)}function Kee(e){return e.end=``,e.plain=e.plain.replaceAll(`
|
|
52
|
+
`,` `),e.expandTabs()}const qee={lastChange:-1/0,nextChange:1/0};var Jee=class{renderable;effect;t;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.t=Ld(`Effected`,n.t),this.key=n.key,this.theme=n.theme}render(e){return this.moved(e).segments}moved(e){let t=kf(this.renderable,e);if(e.colorSystem===null)return{segments:t,hold:qee};let n=e.colorSystem??H.TRUECOLOR,r=Yee(t,n,this.theme),i=Xee(r),a=zf(this.effect($ee(r,()=>i,n,this.theme)),this.t,e);return{segments:this._recolored(i,a.value,n),hold:Bf(a,this.t)}}*_recolored(e,t,n){let r=e.map(({look:e,glyphs:n})=>{if(e===void 0)return;let r=lm(e.style.anchor);if(r?.follows===!0)return{joined:r};let i={fg:e.pair.fg,bg:e.pair.bg,attributes:e.attributes},{terminal:a,reverse:o}=e.pair;return{painted:n.map(({cell:e})=>e===void 0?i:nh(t(i,{...e,seed:Km(this.key,e.row,e.col),terminal:a,reverse:o})))}}),i=Zee(e,r);for(let[a,{segment:o,look:s,glyphs:c}]of e.entries()){let e=r[a];s===void 0||e===void 0?yield o:`joined`in e?yield this._rejoined(o,s,e.joined,c,i,t,n):yield*this._repainted(o,s,c,e.painted,n)}}*_repainted(e,t,n,r,i){let{style:a,wire:o,slots:s,pair:c,attributes:l}=t,u=[];for(let[e,{glyph:t}]of n.entries()){let n=r[e],a=Zm(n,c.reverse),l=u[u.length-1],d=l!==void 0&&tte(l.colors,a)?l.drawn:this.respec(o,s,a,i);l!==void 0&&$m(l.drawn,d)&&ah(l.attributes,n.attributes)?(l.text+=t,l.cells+=B(t),l.colors=a):u.push({text:t,cells:B(t),colors:a,attributes:n.attributes,drawn:d})}if(u.every(e=>$m(e.drawn,o)&&ah(e.attributes,l))){yield e;return}let d=0;for(let e of u){let t=a.shiftedBy(d),n=ah(e.attributes,l)?t:t.withAttributes(ih(e.attributes)),r=$m(e.drawn,o)?n:n.add(W.fromColor(e.drawn.color,e.drawn.bgcolor));yield new G(e.text,r),d+=e.cells}}_rejoined(e,t,n,r,i,a,o){let s=r.flatMap(({cell:e})=>e===void 0?[]:[e]),[c]=s;if(c===void 0)return e;let{theme:l}=this,u=new Set,d=(e,t)=>{if(!e?.isDefault)return e;let n=U.fromRgba(e.getTruecolor(l,t));return u.add(n),n},f=(e,t)=>{let n=Qm(e,t,o,l);return n.fg===void 0&&n.bg===void 0?void 0:{color:d(n.fg,!0),bgcolor:d(n.bg,!1)}},p=e=>{let t=e.drawnColors(o),n={fg:(t.color??qm).getTruecolor(l,!0),bg:(t.bgcolor??qm).getTruecolor(l,!1)},r={fg:t.color?.isDefault??!0,bg:t.bgcolor?.isDefault??!0};return f(n,nh(a({...n,attributes:ih(e)},{...c,seed:Km(this.key,c.row,c.col),terminal:r,reverse:!1})))},m=e=>{let t=n.reads[e];if(t===null)return;let r=i(s,e,t.owner);return r===void 0?p(t.edge):f(r.look.slots,Zm(r.moved,r.look.pair.reverse))},h=n.rederived({left:m(`left`),right:m(`right`)},t.style,o);if(h===void 0)return e;let{colors:g,style:_}=h,v=n.style,y=g.drawnColors(o),{wire:b,slots:x}=t,S=this.respec(b,x,{fg:g.color?.getTruecolor(l,!0)??x.fg,bg:g.bgcolor?.getTruecolor(l,!1)??x.bg},o),C=(e,t,n,r,i)=>{if(ete(e,t))return n;if(e===void 0)throw Error(`a seam cell resolved to ${t?.name??`nothing`} when drawn and to nothing after an effect moved its neighbours`);return u.has(e)?i:r},w={color:C(g.color,v.color,b.color,y.color,S.color),bgcolor:C(g.bgcolor,v.bgcolor,b.bgcolor,y.bgcolor,S.bgcolor)};return new G(e.text,$m(w,b)?_:_.add(W.fromColor(w.color,w.bgcolor)))}measure(e){return If.get(e,this.renderable)}respec(e,t,n,r){let i=Qm(t,n,r,this.theme);return{color:i.fg??e.color,bgcolor:i.bg??e.bgcolor}}},Gm=class e{renderable;effect;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.key=n.key,this.theme=n.theme}at(e){return new Jee(this.renderable,this.effect,{t:e,key:this.key,theme:this.theme})}nextChange(e){return e}lastChange(e){return e}reduced(){let{effect:t}=this;return new e(this.renderable,e=>t(e).reduced(),this)}render(e){let{segments:t,hold:n}=this.at(Uf(e)).moved(e);return Hf(t,n)}measure(e){return If.get(e,this.renderable)}static shows(e,t,n,r){let i=Zm(e,e.reverse),a=Qm(i,Zm(t,e.reverse),n,r);return Zm({fg:a.fg?.getTruecolor(r,!0)??i.fg,bg:a.bg?.getTruecolor(r,!1)??i.bg},e.reverse)}};function Km(e,t,n){return Number.parseInt(up(`${e}:${t}:${n}`),16)/4294967296}const qm=U.default();function Yee(e,t,n){return[...e].map(e=>{if(e.isControl)return{segment:e,look:void 0};let r=e.style??W.null(),i=r.drawnColors(t),a={fg:(i.color??qm).getTruecolor(n,!0),bg:(i.bgcolor??qm).getTruecolor(n,!1)},o=r.reverse===!0,s=Zm({fg:i.color?.isDefault??!0,bg:i.bgcolor?.isDefault??!0},o);return{segment:e,look:{style:r,wire:i,slots:a,pair:{...Zm(a,o),terminal:s,reverse:o},attributes:ih(r),seam:Kd(r.anchor,jp)}}})}function Jm(e){let t=0,n=0;return e.map(e=>{if(e.isControl)return[];let r=e.style?.anchor,i=0;return[...$c(e.text)].map(e=>{let a=e===`
|
|
53
53
|
`?void 0:{row:t,col:n,anchor:r&&Gd(r,i)},o=B(e);return[t,n]=e===`
|
|
54
|
-
`?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Xm(e){return e.trim()!==``}function Yee(e){let t=Ym(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Xee(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&Kd(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&Kd(t.anchor,i))return t}}}function Zee(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Qee(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||Zee(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Xm(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Xm(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Zm(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>K.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function Qm(e,t){return t?{fg:e.bg,bg:e.fg}:e}function $m(e,t,n,r){let i=t.bg.compositeOver(cl),a=t.fg.compositeOver(i);return{fg:U.matchMove(e.fg,a,n,r,!0),bg:U.matchMove(e.bg,i,n,r,!1)}}function eh(e,t){return th(e.color,t.color,!0)&&th(e.bgcolor,t.bgcolor,!1)}function th(e,t,n){return e===t||nh(e,n)===nh(t,n)}function nh(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function rh(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const ih=Jd.filter(e=>e!==`reverse`);function ah(e){return Object.fromEntries(ih.map(t=>[t,e[t]]))}function oh(e,t){return e===t||ih.every(n=>e[n]===t[n])}function $ee(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function ete(e,t){return sh(e.fg,t.fg)&&sh(e.bg,t.bg)}function sh(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const ch=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),lh=e=>e*e*e*(e*(e*6-15)+10),uh=(e,t,n)=>e+n*(t-e);function dh(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function fh(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=lh(e),u=lh(t),d=lh(n),f=ch[o]+s,p=ch[f]+c,m=ch[f+1]+c,h=ch[o+1]+s,g=ch[h]+c,_=ch[h+1]+c;return uh(uh(uh(dh(ch[p],e,t,n),dh(ch[g],e-1,t,n),l),uh(dh(ch[m],e,t-1,n),dh(ch[_],e-1,t-1,n),l),u),uh(uh(dh(ch[p+1],e,t,n-1),dh(ch[g+1],e-1,t,n-1),l),uh(dh(ch[m+1],e,t-1,n-1),dh(ch[_+1],e-1,t-1,n-1),l),u),d)}function tte(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*fh(e*r,t*r,n*r),o+=a,a/=2}return i/o}function ph(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function mh(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const nte=Array.from({length:48},(e,t)=>(t+1)/48);function hh(e,t){return Math.min(ul(e.fg,e.bg),4.5)-(t===H.TRUECOLOR?.01:0)}const gh=[`fg`,`bg`];function rte({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>gh.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>bu.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=gh.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=hh(r,t),c=(t,n)=>bh(i,r[t],(t===a?e:o)*n);return nte.every(e=>{let i=Km.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return ul(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function _h(e,t){let n=new Rc;return yh(ate(e,r=>{let i=t??r.colors,a=[vh(r),`|`,...i].join(` `);return n.get(r.theme,()=>new Lc).get(a,()=>rte(r,i,e.touch))}))}function vh({depth:e,pairs:t}){return[e,...t.map(ite)].join(` `)}function ite({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function ate(e,t){return n=>{let r=t(n);return K.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(Th(i(n))*48)/48,o=(t,n)=>bh(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function yh(e){return t=>ote(t.depth)?K.constant(e=>e):e(t)}function ote(e){switch(e){case H.DEFAULT:case H.STANDARD:case H.WINDOWS:return!0;case H.EIGHT_BIT:case H.TRUECOLOR:return!1}}function bh(e,t,n){return n===0?t:e(t,n)}function xh(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}function Sh(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const Ch={shimmer:{seconds:109,ease:Md.linear,swing:.9},pulse:{seconds:43,ease:Md.linear,swing:.85},sparkle:{seconds:139,ease:Md.linear,swing:.95},wheel:{seconds:907,ease:Md.linear,swing:1},fade:{seconds:20,ease:Md[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:Md[`ease-in-out`],swing:1}},wh={sun:new V(255,228,176),firefly:new V(222,245,140)},Th=e=>Math.min(1,Math.max(0,e));function Eh(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new bu((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Dh(e){let t=bu.fromRgba(e);return(e,n)=>{let r=bu.fromRgba(e);return Eh(r,new bu(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Oh=(e,t)=>t*e[e.length-1][0];function kh(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function ste(e,t,n){let r=Oh(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=kh(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const Ah=[[.24,1],[.6,0]];function cte(e,t,n){xh(e),Sh(`pulse`,n);let r=.9+.2*ph(n,3.1),i=t=>.1*fh(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Dh(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*mh(-.5,.5,fh(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const jh=e=>Math.abs(e)>=1?0:(1-e*e)**3;function lte(e,t,n,r){xh(e),Sh(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>mh(-.4,.4,fh(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(ph(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*ph(e,8.5+r))),p=i*u/80*(c+l*ph(e,5.5+r)),m=Th((n-(e+s*ph(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*fh(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((fh(e,t,n)/.8)**2));return{touch:Dh(n),field:(n,i)=>{let[a,o]=Ih(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*jh((i.col-a-n)/t));let c=i.row+r,l=.8*fh(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function ute(e,t,n){xh(e),Sh(`sparkle`,n);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*fh(e*1.7+.2,.3+t*2.9,.5+n),l=i+ph(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=ph(u,s+1)<.15?0:1,f=.5+.5*ph(u,s+2),p=ph(u,s+3)*(1-Oh(Ah,f)),m=l/r-u-p;return{x:a+c*8+5*(2*ph(u,s+4)-1)+5*f*(2*ph(u,s+5)-1)*ste(Ah,m,f)+1.5*fh(s,.1,i*.035),y:o+t*3+.6*fh(s,2.2,i*.035),glow:d*kh(Ah,m,f)}};return{touch:Dh(t),field:(t,n)=>{let r=n.cells(),[s,c]=Ih(r.map(e=>e.col)),[l,u]=Ih(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*jh(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Mh(e,t){return n=>{let r=bu.fromRgba(n.theme.backgroundColor);return K.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-Th(a(n)));if(i===0)return e;let o=Eh(bu.fromRgba(e.bg),r,i);return{...e,fg:Eh(bu.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Nh(e){return t=>Th(.5+1.1*tte(t.col*.09+1.4*fh(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var dte=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return K.done(this.schedule,e)}};function Ph(e,t){let n=K.of({...K.sequence(K.continuous(()=>void 0),e,K.constant(void 0)),reduced:()=>K.cut(void 0,void 0)}),r=new dte(i=>{let a=t(i);return K.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>K.cut(a.at(0),a.at(e))})},n);return r}function Fh(e,t){return(n,r)=>{let[i,a]=Ih(r.map(t)),o=(a>i?.55:0)*e.seconds,s=Wd.once(0,e.seconds-o);return e=>{let r=a>i?Th((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function Ih(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function fte(e,t){xh(e),Sh(`fadeIn`,t);let n=Fh(e,Nh(1.7+t));return Ph(e.seconds,Mh((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const pte={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function mte(e,t){xh(e),Sh(`dissolveOut`,t);let n=Nh(9.3+t),r=Fh(e,Nh(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=pte;return Ph(e.seconds,Mh((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=Th((f-a)/(o-a)),m=i*mh(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Lh=[211,337],hte=(e,t)=>({row:e.row,centre:e.col+t/2});function Rh(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?hte(e,a):p(o)}}function zh(e,t){xh(e),Sh(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>fh(r/Lh[0],n/24+5.9,t+e/24+2.3)+.5*fh(r/Lh[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new Rc;return yh(e=>{let{colors:t,fills:n,depth:r,theme:o}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=a.get(o,()=>new Lc).get(vh(e),()=>Gh(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),d=Jh(r,o),f=Rh(e);return K.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=Bh(t,i(a,e));return Yh(o.looks,t,r===H.TRUECOLOR?o.either.map(Kh):d,u.get(l(t,n))??Hh)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Bh(e,t){if(t===0)return{looks:e,either:[e]};let n=bu.fromRgba(e),r=ll(e),i=e=>new bu(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=ll(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Vh=e=>Math.log(ul(e,new V(0,0,0))),Hh={lo:-1/0,hi:1/0},Uh={lo:1/0,hi:-1/0},Wh=Math.log(1.031);function Gh(e,t,n){let r=new Map;for(let i of e.filter(e=>hh(e,t)>1)){let e=(Math.log(ul(i.fg,i.bg))-Math.log(hh(i,t)))/gh.filter(e=>n(i,e)!==void 0).length;for(let t of gh){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Vh(i[t]),Vh(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Hh;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<Wh?Uh:{lo:t,hi:n}]))}const Kh=e=>({color:e,looks:bu.fromRgba(e),stop:Vh(e)}),qh=new Rc;function Jh(e,t){return qh.get(U.indexed(e,t),e=>e.map(([,e])=>Kh(e)))}function Yh(e,t,n,{lo:r,hi:i}){return Xh(e,[Kh(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function Xh(e,t){let n=bu.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}function Zh({attribute:e,off:t,on:n}){let r=Ud([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>K.map(r,e=>i[e])}const Qh={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},$h={loops:{shimmer:(e,t=Ch.shimmer)=>_h(lte(t,24,wh.sun,e.z)),pulse:(e,t=Ch.pulse)=>_h(cte(t,wh.sun,e.z)),sparkle:(e,t=Ch.sparkle)=>_h(ute(t,wh.firefly,e.z)),wheel:(e,t=Ch.wheel)=>zh(t,e.z)},transitions:{fade:(e,t=Ch.fade)=>fte(t,e.z),dissolve:(e,t=Ch.dissolve)=>mte(t,e.z)},attributes:{blink:()=>Zh(Qh.blink),boldPulse:()=>Zh(Qh.boldPulse)}};function eg(e,t){let n=0,r=Ym(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:qm(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function tg(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:ag(t,n)));return og(e.flat(),n.flat()),n}function ng(e,t,n){let{placed:r,cells:i}=eg([new G(e.plain)],n.key);return K.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>rg(e,r[0],tg(r,t)[0]))}function rg(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const ig=zc(/[\n\t]/);function ag(e,t){let n=e(t);if(n===t.glyph)return n;if(B(n)!==B(t.glyph)||ig.test(n)||vp(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${B(t.glyph)} cell(s) wide, with no line break or control character`);return n}function og(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if($c(o+t+s).length!==$c(o).length+$c(t).length+$c(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function sg(e){return` `.repeat(B(e))}function cg(e){let t=new Map;for(let n of e.filter(e=>Xm(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&B(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function lg(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function ug(e){let t=Ud([e]);return(n,r)=>K.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>K.constant(r)})}const dg=e=>e.glyph;function fg(e){let t=Wd.once(0,e.seconds),n=Dd(e.ease);return Ph(e.seconds,({cells:e})=>{let{length:r,place:i}=cg(e);return K.continuous(e=>{let a=lg(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:sg(e.glyph)})})}const pg=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],mg=1/15;function hg(e,t){Sh(`scramble`,t);let n=Wd.once(0,e.seconds),r=Dd(e.ease),i=ug(mg)(e=>e,0);return Ph(e.seconds,({cells:e})=>{let{length:a,place:o}=cg(e);return K.continuous(e=>{let s=lg(a,r(n(e))),c=i.at(e);return e=>!Xm(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:gg(e,t,c)})})}function gg(e,t,n){let r=r=>pg[Math.floor(ph(e.seed*7919+r,t+n*.618)*pg.length)];return Array.from({length:B(e.glyph)},(e,t)=>r(t)).join(``)}function _g(e){let t=Wd.once(0,e.seconds),n=Dd(e.ease);return Ph(e.seconds,({cells:e})=>{let{length:r,place:i}=cg(e);return K.continuous(e=>{let a=r-lg(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:sg(e.glyph)})})}const vg=.3;function yg(e,t){Sh(`scrambleOut`,t);let n=Wd.once(0,e.seconds),r=Dd(e.ease),i=ug(mg)(e=>e,0);return Ph(e.seconds,({cells:e})=>{let{length:a,place:o}=cg(e);return K.continuous(e=>{let s=r(n(e)),c=lg(a,s/(1-vg)),l=lg(a,(s-vg)/(1-vg)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?sg(e.glyph):!Xm(e.glyph)||n>=c?e.glyph:gg(e,t,u)}})})}function bg(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return B(t)===B(e)?t:e}function xg({step:e,width:t},n){if(Fd(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);Sh(`caseWave`,n);let r=ug(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+B(t.glyph)),0)+t,a=Math.floor(ph(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+B(e.glyph)>n-t?bg(e.glyph):e.glyph},dg)}}function Sg(e,t){let n=e=>{let t=$c(e);if(t.length===0||t.some(e=>B(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!gf(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);Fd(`particles step`,e.step),Sh(`particles`,t);let a=ug(e.step);return({asciiOnly:n})=>{let o=_f({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Xm(n.glyph)||B(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return ph(a,s)<e.density?o[Math.floor(ph(a,s+3.1)*o.length)]+sg(n.glyph).slice(1):n.glyph}},dg)}}const Cg={typewriter:{seconds:2,ease:Md.linear},scramble:{seconds:2.5,ease:Md[`ease-in`]},backspace:{seconds:1.5,ease:Md.linear},scrambleOut:{seconds:2.5,ease:Md[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},wg={loops:{wave:e=>xg(Cg.wave,e.z),rain:e=>Sg(Cg.rain,e.z),stars:e=>Sg(Cg.stars,e.z)},transitions:{typewriter:(e,t=Cg.typewriter)=>fg(t),scramble:(e,t=Cg.scramble)=>hg(t,e.z),backspace:(e,t=Cg.backspace)=>_g(t),scrambleOut:(e,t=Cg.scrambleOut)=>yg(t,e.z)}};var Tg=class{beat;width;_shown;constructor(e){this.beat=Ud(e.map(e=>e.seconds));let t=e.map(e=>Gm(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}reduced(){return K.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return Kf(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function Eg(e,t,n){let r=zf(e,t,n),i=r.value.copy();return i.style=nf(i.style,Vf(Bf(r,t))),i}function Dg(e,t){let n=[...kf(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const Og={segments:[],width:0},kg={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function Ag(e,t){return kg[e](t)}function jg(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var Mg=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>Dg(Np(t),e)),o=n=>i?Dg(Mp(i,null,t[n],{index:n}),e):Og,s=n=>i?Dg(Mp(i,t[n],null,{index:n+1}),e):Og,c=(n,r)=>i?Dg(Mp(i,t[n],t[r],{index:r}),e):Og,l=[],u=null,d=r>0?{segments:[new G(` `.repeat(r))],width:r}:Og;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=Ag(p,i),o=jg(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new G(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new G(` `.repeat(e)))}yield*t.blocks[e].segments}yield G.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=Dg(t[i],e).width,o=this.joiner?Dg(Mp(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?Dg(Mp(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=Dg(Mp(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=Dg(Mp(this.joiner,null,t[0],{index:0}),e).width,r+=Dg(Mp(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function Ng(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const Pg=(e,t)=>e===t;function Fg(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const Ig=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),Lg=[`primary`,`secondary`,`accent`],Rg=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],zg={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},Bg=(e,t)=>`${e}${zg[t]}`,Vg=(e,t,n,r)=>F_(e,n,r),Hg=(e,t,n,r)=>L_(e,e.get(`text-${t}`),n,r),Ug=e=>({tones:[Rg[e],Rg[e+2],Rg[e+1]],text:Vg,activated:`muted`}),Wg=e=>({tones:[Rg[3-e],Rg[3+e],Rg[3]],text:Vg,activated:`muted`}),Gg=e=>({tones:[Rg[3-e],Rg[3+e]],text:Vg,activated:`muted`}),Kg={wide:Wg(2),widest:Wg(3),pair:Gg(2),"pair-wide":Gg(3)},qg=Object.keys(Kg),Jg={muted:{tones:[`muted`,`base`],text:Hg,activated:`lighten-2`},deepest:Ug(0),deeper:Ug(1),middle:Ug(2),brighter:Ug(3),brightest:Ug(4),...Kg},Yg=(e,t)=>e[t%e.length],Xg=`accent`,Zg=1/0,Qg={keystones:[],open:[`accent`,`primary`,`secondary`]},$g={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},e_={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function t_(){let e=Object.entries($g).flatMap(([e,t])=>Object.entries(e_).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:Zg,keystones:t,open:r}]));return Object.fromEntries(e)}const n_=t_(),r_={accent:{hues:[`secondary`,`accent`],run:Zg,...Qg},duo:{hues:[`primary`,`secondary`],run:Zg,...Qg},mono:{hues:[`primary`],run:Zg,...Qg},alt:{hues:[`secondary`,`accent`],run:3,...Qg},...n_},i_=Object.keys(n_),a_=(e,t,n)=>j_(e,t,t.variation.hues.flatMap(r=>{let i=o_(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function o_(e,t,n,r){return l_(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=u_(e,t,r),a=c_(n.tones.length,new Set(Rg.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return s_(Array.from({length:a-c.length}).reduce(a=>{let o=d_(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const s_=e=>{if(e.length<3)return e;let t=Rg,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},c_=(e,t)=>Math.max(2,Math.min(e,t-1)),l_=Ng(),u_=(e,t,n)=>r=>Ru(e.get(Bg(t,r)),n).hex;function d_(e,t,n,r,i){let a=u_(e,t,i);return f_(n,e.dark).find(e=>!r.includes(a(e)))}function f_(e,t){let n=Rg,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return Rg.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const p_=(e,t)=>Math.floor(e*t),m_=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},h_=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},g_=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],__=e=>typeof e==`string`&&g_.includes(e),v_={"van-der-corput":{place:h_,quantize:m_},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:p_},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:p_},monotonic:{place:(e,t)=>(e+.5)/t,quantize:p_},uniform:{place:()=>.5,quantize:m_}},y_=e=>v_[e??`van-der-corput`];function b_(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function x_(e,t){let n=e[b_(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function S_(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const C_=(e,t)=>b_(t,e.hues.length);function w_(e,t,n,r){let{row:i,cell:a}=S_(n);return a===void 0?T_(e,t,i,a,r):E_(e,t,i,a,r)[a.index-a.lineStart]}function T_(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(C_(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>M_[e](n,r))?Xg:l;return{hue:u,shade:x_(o_(e,u,t.shade,i),r)}}function E_(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return D_(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:O_(n),O_(r,r.lineStart),i].join(`|`),()=>j_(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>T_(e,t,n,{...r,index:r.lineStart+o},i)),i))}const D_=Ng();function O_({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${k_(r)},${i},${a}`}function k_(e){let t=A_.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const A_=new Map(g_.map(e=>[v_[e],e]));function j_(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&u_(e,n.hue,r)(n.shade)},o=U_(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=o_(e,s,t.shade,r),u=l.find(t=>!c.includes(u_(e,s,r)(t)))??d_(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const M_={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},N_=(e,t)=>e.get(Bg(t.hue,t.shade)),P_=4.5;function F_(e,t,n){return I_(e,`${t.hex}|${n}`,()=>{let r=Fu(t);return L_(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>ul(r,t)<ul(r,e)?t:e),t,n)})}const I_=Ng();function L_(e,t,n,r){return R_(e,`${t.hex}|${n.hex}|${r}`,()=>Iu(t,n,P_,r))}const R_=Ng(),z_=({decor:e,depth:t})=>Yg(e.variation.open,t),B_=(e,t,n)=>o_(e,z_(t),t.decor.shade,n).map(e=>({hue:z_(t),shade:e}));function V_(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return H_(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=z_(t),c=t=>o_(e,t,o,n).map(u_(e,t,n)),l=a.keystones.length>0?[Xg]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(z_(t)),U_(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(u_(e,s,n)(o.activated))?d_(e,s,[o.activated],d,n)??o.activated:o.activated})}const H_=Ng(),U_=(e,t,n)=>u_(e,z_(t),n)(V_(e,t,n)),W_=e=>({...e,depth:e.depth+1});function G_(e,t,n){return{state:e.get(Bg(z_(t),V_(e,t,n))),plane:e.get(`surface`),items:B_(e,t,n).map(t=>N_(e,t))}}function K_(e,t,n,r){return x_(G_(e,t,r).items,n)}function q_(e,t,n,r){let i=K_(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,z_(t),i,r)}}function J_(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&Q_(e,t);case`band`:return t.kind===`band`&&$_(e,t)}}const Y_=Ig(Fg({index:Pg,count:Pg,distribution:Pg,axis:Pg,lineStart:Pg,lineEnd:Pg})),X_=Fg({variation:Pg,shade:Pg}),Z_=Fg({decor:X_,depth:Pg}),Q_=Fg({kind:Pg,decor:X_,address:Y_}),$_=Fg({kind:Pg,band:Z_,address:Y_}),ev=e=>({kind:`bar`,decor:e,address:[]}),tv=(e,t)=>({...e,address:[...e.address,t]}),nv=e=>({kind:`band`,band:e,address:[]});function rv(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=w_(e,r,i,n),o=N_(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...q_(e,r,S_(i).cell,n),disclosure:W_(r)}}}}const iv=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function av(e){let t=typeof e==`string`?iv.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const ov=`textual-dark`;function sv(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function cv(){return xd()}function lv(){return[`bar`,...cv()]}let uv;function dv(e){return uv??=new Set(lv()),uv.has(e)}function fv(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return sv(e===void 0?null:a(e),t,a(n??r),r,a)}const pv=[`style`,`palette`,`effect`];function mv(e){return e!==void 0&&e.includes(`{{`)}function hv(e,t,n,r,i){let a=mv(n)?{kind:`expression`,source:n}:i(n??r.name);return sv(e===void 0?null:i(e),t,a,r,i)}const gv=`none`;function _v(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function vv(e,t){return _v(e,t)??_v(`none`,t)??{kind:`decided`,name:`none`,value:cu}}function yv(e,t,n,r){return hv(e,t,n,vv(gv,r),e=>_v(e,r))}const bv=`none`,xv={style:gv,palette:ov,effect:bv};function Sv(e,t,n){return`${e} rendered "${xv[t]}": ${n}`}const Cv=Object.freeze([bv,...Object.keys($h.loops)]),wv=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),Tv=Object.keys(wv),Ev=Object.freeze([`bar`,...Cv]);function Dv(e){let t=Cv.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Ov(e){return Dv(e)??{kind:`decided`,name:`none`,value:`none`}}function kv(e,t,n){return hv(e,t,n,Ov(bv),Dv)}const Av=Object.freeze(Object.keys(Vm)),jv=[`powerline`,`capsule`,`plain`];function Mv(e){return jv.includes(e)}const Nv=[`truecolor`,`256`,`ansi`,`none`];function Pv(e){return Nv.includes(e)}function Fv(e){return Cl(e)??H.DEFAULT}const Iv=Object.keys(r_),Lv=Object.keys(Jg),Rv=`true`,zv=`false`,Bv=[Rv,zv],Vv={min:0,max:16};function Hv(e){return e===`true`?!0:e===`false`?!1:null}function Uv(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}function Wv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gv(e){return ce(`sha256`).update(JSON.stringify(Kv(e))).digest(`hex`)}function Kv(e){return Array.isArray(e)?e.map(Kv):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,Kv(t)])):e}const qv=[`vertical`,`horizontal`],Jv={vertical:`row`,horizontal:`cell`};function Yv(e){return e.id??e.name}function Xv(e){return[...$v(e)].flatMap(e=>e.kind===`segment`?[Yv(e)]:[])}function Zv(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Qv(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*$v(e){yield e;for(let t of ry(e))yield*$v(t)}const ey=(e,t)=>`${e}.children[${t}]`,ty=e=>`${e}.opens.body`;function*ny(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*ny(r,ey(t,n));else e.opens!==void 0&&(yield*ny(e.opens.body,ty(t)))}function ry(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function iy(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const ay=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function oy(e){return e.kind===`file`||e.kind===`shell`}function sy(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return oy(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function cy(e){let t=[];return sy(e,(e,n)=>(t.push([n,e]),e)),t}const ly=[`fail`,`ignore`];function uy(e){return e.missingData??`fail`}function*dy(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const fy=`theme`,py=`effect`,my=[fy,py];function hy(e){return{...e.settings,[fy]:{label:fy,domain:`theme`,default:e.palette??`bar`},[py]:{label:py,domain:Ev,default:`bar`}}}function gy(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function _y(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=gy(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function vy(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&dv(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function yy(e){return String(e)}function by(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Uv(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return vy(e,r)?r:void 0}function xy(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:by(n,o))??i}function Sy(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Cy=[`left`,`center`,`right`],wy=[`right`,`left`,`middle`];var Ty=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Fy(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},Ey=class extends Ty{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
|
|
54
|
+
`?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Ym(e){return e.trim()!==``}function Xee(e){let t=Jm(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Zee(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&Kd(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&Kd(t.anchor,i))return t}}}function Qee(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function $ee(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||Qee(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Ym(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Ym(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Xm(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>K.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function Zm(e,t){return t?{fg:e.bg,bg:e.fg}:e}function Qm(e,t,n,r){let i=t.bg.compositeOver(cl),a=t.fg.compositeOver(i);return{fg:U.matchMove(e.fg,a,n,r,!0),bg:U.matchMove(e.bg,i,n,r,!1)}}function $m(e,t){return eh(e.color,t.color,!0)&&eh(e.bgcolor,t.bgcolor,!1)}function eh(e,t,n){return e===t||th(e,n)===th(t,n)}function th(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function nh(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const rh=Jd.filter(e=>e!==`reverse`);function ih(e){return Object.fromEntries(rh.map(t=>[t,e[t]]))}function ah(e,t){return e===t||rh.every(n=>e[n]===t[n])}function ete(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function tte(e,t){return oh(e.fg,t.fg)&&oh(e.bg,t.bg)}function oh(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const sh=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),ch=e=>e*e*e*(e*(e*6-15)+10),lh=(e,t,n)=>e+n*(t-e);function uh(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function dh(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=ch(e),u=ch(t),d=ch(n),f=sh[o]+s,p=sh[f]+c,m=sh[f+1]+c,h=sh[o+1]+s,g=sh[h]+c,_=sh[h+1]+c;return lh(lh(lh(uh(sh[p],e,t,n),uh(sh[g],e-1,t,n),l),lh(uh(sh[m],e,t-1,n),uh(sh[_],e-1,t-1,n),l),u),lh(lh(uh(sh[p+1],e,t,n-1),uh(sh[g+1],e-1,t,n-1),l),lh(uh(sh[m+1],e,t-1,n-1),uh(sh[_+1],e-1,t-1,n-1),l),u),d)}function nte(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*dh(e*r,t*r,n*r),o+=a,a/=2}return i/o}function fh(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function ph(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const rte=Array.from({length:48},(e,t)=>(t+1)/48);function mh(e,t){return Math.min(ul(e.fg,e.bg),4.5)-(t===H.TRUECOLOR?.01:0)}const hh=[`fg`,`bg`];function ite({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>hh.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>bu.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=hh.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=mh(r,t),c=(t,n)=>yh(i,r[t],(t===a?e:o)*n);return rte.every(e=>{let i=Gm.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return ul(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function gh(e,t){let n=new Rc;return vh(ote(e,r=>{let i=t??r.colors,a=[_h(r),`|`,...i].join(` `);return n.get(r.theme,()=>new Lc).get(a,()=>ite(r,i,e.touch))}))}function _h({depth:e,pairs:t}){return[e,...t.map(ate)].join(` `)}function ate({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function ote(e,t){return n=>{let r=t(n);return K.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(wh(i(n))*48)/48,o=(t,n)=>yh(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function vh(e){return t=>ste(t.depth)?K.constant(e=>e):e(t)}function ste(e){switch(e){case H.DEFAULT:case H.STANDARD:case H.WINDOWS:return!0;case H.EIGHT_BIT:case H.TRUECOLOR:return!1}}function yh(e,t,n){return n===0?t:e(t,n)}function bh(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}function xh(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const Sh={shimmer:{seconds:109,ease:Md.linear,swing:.9},pulse:{seconds:43,ease:Md.linear,swing:.85},sparkle:{seconds:139,ease:Md.linear,swing:.95},wheel:{seconds:907,ease:Md.linear,swing:1},fade:{seconds:20,ease:Md[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:Md[`ease-in-out`],swing:1}},Ch={sun:new V(255,228,176),firefly:new V(222,245,140)},wh=e=>Math.min(1,Math.max(0,e));function Th(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new bu((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Eh(e){let t=bu.fromRgba(e);return(e,n)=>{let r=bu.fromRgba(e);return Th(r,new bu(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Dh=(e,t)=>t*e[e.length-1][0];function Oh(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function cte(e,t,n){let r=Dh(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Oh(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const kh=[[.24,1],[.6,0]];function lte(e,t,n){bh(e),xh(`pulse`,n);let r=.9+.2*fh(n,3.1),i=t=>.1*dh(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Eh(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*ph(-.5,.5,dh(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const Ah=e=>Math.abs(e)>=1?0:(1-e*e)**3;function ute(e,t,n,r){bh(e),xh(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>ph(-.4,.4,dh(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(fh(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*fh(e,8.5+r))),p=i*u/80*(c+l*fh(e,5.5+r)),m=wh((n-(e+s*fh(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*dh(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((dh(e,t,n)/.8)**2));return{touch:Eh(n),field:(n,i)=>{let[a,o]=Fh(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*Ah((i.col-a-n)/t));let c=i.row+r,l=.8*dh(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function dte(e,t,n){bh(e),xh(`sparkle`,n);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*dh(e*1.7+.2,.3+t*2.9,.5+n),l=i+fh(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=fh(u,s+1)<.15?0:1,f=.5+.5*fh(u,s+2),p=fh(u,s+3)*(1-Dh(kh,f)),m=l/r-u-p;return{x:a+c*8+5*(2*fh(u,s+4)-1)+5*f*(2*fh(u,s+5)-1)*cte(kh,m,f)+1.5*dh(s,.1,i*.035),y:o+t*3+.6*dh(s,2.2,i*.035),glow:d*Oh(kh,m,f)}};return{touch:Eh(t),field:(t,n)=>{let r=n.cells(),[s,c]=Fh(r.map(e=>e.col)),[l,u]=Fh(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*Ah(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function jh(e,t){return n=>{let r=bu.fromRgba(n.theme.backgroundColor);return K.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-wh(a(n)));if(i===0)return e;let o=Th(bu.fromRgba(e.bg),r,i);return{...e,fg:Th(bu.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Mh(e){return t=>wh(.5+1.1*nte(t.col*.09+1.4*dh(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var fte=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return K.done(this.schedule,e)}};function Nh(e,t){let n=K.of({...K.sequence(K.continuous(()=>void 0),e,K.constant(void 0)),reduced:()=>K.cut(void 0,void 0)}),r=new fte(i=>{let a=t(i);return K.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>K.cut(a.at(0),a.at(e))})},n);return r}function Ph(e,t){return(n,r)=>{let[i,a]=Fh(r.map(t)),o=(a>i?.55:0)*e.seconds,s=Wd.once(0,e.seconds-o);return e=>{let r=a>i?wh((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function Fh(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function pte(e,t){bh(e),xh(`fadeIn`,t);let n=Ph(e,Mh(1.7+t));return Nh(e.seconds,jh((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const mte={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function hte(e,t){bh(e),xh(`dissolveOut`,t);let n=Mh(9.3+t),r=Ph(e,Mh(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=mte;return Nh(e.seconds,jh((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=wh((f-a)/(o-a)),m=i*ph(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Ih=[211,337],gte=(e,t)=>({row:e.row,centre:e.col+t/2});function _te(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?gte(e,a):p(o)}}function Lh(e,t){bh(e),xh(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>dh(r/Ih[0],n/24+5.9,t+e/24+2.3)+.5*dh(r/Ih[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new Rc;return vh(e=>{let{colors:t,fills:n,depth:r,theme:o}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=a.get(o,()=>new Lc).get(_h(e),()=>Uh(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),d=Kh(r,o),f=_te(e);return K.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=Rh(t,i(a,e));return qh(o.looks,t,r===H.TRUECOLOR?o.either.map(Wh):d,u.get(l(t,n))??Bh)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Rh(e,t){if(t===0)return{looks:e,either:[e]};let n=bu.fromRgba(e),r=ll(e),i=e=>new bu(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=ll(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const zh=e=>Math.log(ul(e,new V(0,0,0))),Bh={lo:-1/0,hi:1/0},Vh={lo:1/0,hi:-1/0},Hh=Math.log(1.031);function Uh(e,t,n){let r=new Map;for(let i of e.filter(e=>mh(e,t)>1)){let e=(Math.log(ul(i.fg,i.bg))-Math.log(mh(i,t)))/hh.filter(e=>n(i,e)!==void 0).length;for(let t of hh){let a=n(i,t);if(a===void 0)continue;let[o,s]=[zh(i[t]),zh(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Bh;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<Hh?Vh:{lo:t,hi:n}]))}const Wh=e=>({color:e,looks:bu.fromRgba(e),stop:zh(e)}),Gh=new Rc;function Kh(e,t){return Gh.get(U.indexed(e,t),e=>e.map(([,e])=>Wh(e)))}function qh(e,t,n,{lo:r,hi:i}){return Jh(e,[Wh(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function Jh(e,t){let n=bu.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}function Yh({attribute:e,off:t,on:n}){let r=Ud([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>K.map(r,e=>i[e])}const Xh={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},Zh={loops:{shimmer:(e,t=Sh.shimmer)=>gh(ute(t,24,Ch.sun,e.z)),pulse:(e,t=Sh.pulse)=>gh(lte(t,Ch.sun,e.z)),sparkle:(e,t=Sh.sparkle)=>gh(dte(t,Ch.firefly,e.z)),wheel:(e,t=Sh.wheel)=>Lh(t,e.z)},transitions:{fade:(e,t=Sh.fade)=>pte(t,e.z),dissolve:(e,t=Sh.dissolve)=>hte(t,e.z)},attributes:{blink:()=>Yh(Xh.blink),boldPulse:()=>Yh(Xh.boldPulse)}};function Qh(e,t){let n=0,r=Jm(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:Km(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function $h(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:rg(t,n)));return ig(e.flat(),n.flat()),n}function eg(e,t,n){let{placed:r,cells:i}=Qh([new G(e.plain)],n.key);return K.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>tg(e,r[0],$h(r,t)[0]))}function tg(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const ng=zc(/[\n\t]/);function rg(e,t){let n=e(t);if(n===t.glyph)return n;if(B(n)!==B(t.glyph)||ng.test(n)||vp(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${B(t.glyph)} cell(s) wide, with no line break or control character`);return n}function ig(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if($c(o+t+s).length!==$c(o).length+$c(t).length+$c(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function ag(e){return` `.repeat(B(e))}function og(e){let t=new Map;for(let n of e.filter(e=>Ym(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&B(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function sg(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function cg(e){let t=Ud([e]);return(n,r)=>K.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>K.constant(r)})}const lg=e=>e.glyph;function ug(e){let t=Wd.once(0,e.seconds),n=Dd(e.ease);return Nh(e.seconds,({cells:e})=>{let{length:r,place:i}=og(e);return K.continuous(e=>{let a=sg(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:ag(e.glyph)})})}const dg=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],fg=1/15;function pg(e,t){xh(`scramble`,t);let n=Wd.once(0,e.seconds),r=Dd(e.ease),i=cg(fg)(e=>e,0);return Nh(e.seconds,({cells:e})=>{let{length:a,place:o}=og(e);return K.continuous(e=>{let s=sg(a,r(n(e))),c=i.at(e);return e=>!Ym(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:mg(e,t,c)})})}function mg(e,t,n){let r=r=>dg[Math.floor(fh(e.seed*7919+r,t+n*.618)*dg.length)];return Array.from({length:B(e.glyph)},(e,t)=>r(t)).join(``)}function hg(e){let t=Wd.once(0,e.seconds),n=Dd(e.ease);return Nh(e.seconds,({cells:e})=>{let{length:r,place:i}=og(e);return K.continuous(e=>{let a=r-sg(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:ag(e.glyph)})})}const gg=.3;function _g(e,t){xh(`scrambleOut`,t);let n=Wd.once(0,e.seconds),r=Dd(e.ease),i=cg(fg)(e=>e,0);return Nh(e.seconds,({cells:e})=>{let{length:a,place:o}=og(e);return K.continuous(e=>{let s=r(n(e)),c=sg(a,s/(1-gg)),l=sg(a,(s-gg)/(1-gg)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?ag(e.glyph):!Ym(e.glyph)||n>=c?e.glyph:mg(e,t,u)}})})}function vg(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return B(t)===B(e)?t:e}function yg({step:e,width:t},n){if(Fd(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);xh(`caseWave`,n);let r=cg(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+B(t.glyph)),0)+t,a=Math.floor(fh(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+B(e.glyph)>n-t?vg(e.glyph):e.glyph},lg)}}function bg(e,t){let n=e=>{let t=$c(e);if(t.length===0||t.some(e=>B(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!gf(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);Fd(`particles step`,e.step),xh(`particles`,t);let a=cg(e.step);return({asciiOnly:n})=>{let o=_f({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Ym(n.glyph)||B(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return fh(a,s)<e.density?o[Math.floor(fh(a,s+3.1)*o.length)]+ag(n.glyph).slice(1):n.glyph}},lg)}}const xg={typewriter:{seconds:2,ease:Md.linear},scramble:{seconds:2.5,ease:Md[`ease-in`]},backspace:{seconds:1.5,ease:Md.linear},scrambleOut:{seconds:2.5,ease:Md[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},Sg={loops:{wave:e=>yg(xg.wave,e.z),rain:e=>bg(xg.rain,e.z),stars:e=>bg(xg.stars,e.z)},transitions:{typewriter:(e,t=xg.typewriter)=>ug(t),scramble:(e,t=xg.scramble)=>pg(t,e.z),backspace:(e,t=xg.backspace)=>hg(t),scrambleOut:(e,t=xg.scrambleOut)=>_g(t,e.z)}};var Cg=class{beat;width;_shown;constructor(e){this.beat=Ud(e.map(e=>e.seconds));let t=e.map(e=>Kee(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}reduced(){return K.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return Kf(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function wg(e,t,n){let r=zf(e,t,n),i=r.value.copy();return i.style=nf(i.style,Vf(Bf(r,t))),i}function Tg(e,t){let n=[...kf(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const Eg={segments:[],width:0},Dg={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function Og(e,t){return Dg[e](t)}function kg(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var Ag=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>Tg(Np(t),e)),o=n=>i?Tg(Mp(i,null,t[n],{index:n}),e):Eg,s=n=>i?Tg(Mp(i,t[n],null,{index:n+1}),e):Eg,c=(n,r)=>i?Tg(Mp(i,t[n],t[r],{index:r}),e):Eg,l=[],u=null,d=r>0?{segments:[new G(` `.repeat(r))],width:r}:Eg;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=Og(p,i),o=kg(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new G(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new G(` `.repeat(e)))}yield*t.blocks[e].segments}yield G.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=Tg(t[i],e).width,o=this.joiner?Tg(Mp(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?Tg(Mp(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=Tg(Mp(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=Tg(Mp(this.joiner,null,t[0],{index:0}),e).width,r+=Tg(Mp(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function jg(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const Mg=(e,t)=>e===t;function Ng(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const Pg=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),Fg=[`primary`,`secondary`,`accent`],Ig=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],Lg={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},Rg=(e,t)=>`${e}${Lg[t]}`,zg=(e,t,n,r)=>N_(e,n,r),Bg=(e,t,n,r)=>F_(e,e.get(`text-${t}`),n,r),Vg=e=>({tones:[Ig[e],Ig[e+2],Ig[e+1]],text:zg,activated:`muted`}),Hg=e=>({tones:[Ig[3-e],Ig[3+e],Ig[3]],text:zg,activated:`muted`}),Ug=e=>({tones:[Ig[3-e],Ig[3+e]],text:zg,activated:`muted`}),Wg={wide:Hg(2),widest:Hg(3),pair:Ug(2),"pair-wide":Ug(3)},Gg=Object.keys(Wg),Kg={muted:{tones:[`muted`,`base`],text:Bg,activated:`lighten-2`},deepest:Vg(0),deeper:Vg(1),middle:Vg(2),brighter:Vg(3),brightest:Vg(4),...Wg},qg=(e,t)=>e[t%e.length],Jg=`accent`,Yg=1/0,Xg={keystones:[],open:[`accent`,`primary`,`secondary`]},Zg={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},Qg={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function $g(){let e=Object.entries(Zg).flatMap(([e,t])=>Object.entries(Qg).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:Yg,keystones:t,open:r}]));return Object.fromEntries(e)}const e_=$g(),t_={accent:{hues:[`secondary`,`accent`],run:Yg,...Xg},duo:{hues:[`primary`,`secondary`],run:Yg,...Xg},mono:{hues:[`primary`],run:Yg,...Xg},alt:{hues:[`secondary`,`accent`],run:3,...Xg},...e_},n_=Object.keys(e_),r_=(e,t,n)=>k_(e,t,t.variation.hues.flatMap(r=>{let i=i_(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function i_(e,t,n,r){return s_(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=c_(e,t,r),a=o_(n.tones.length,new Set(Ig.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return a_(Array.from({length:a-c.length}).reduce(a=>{let o=l_(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const a_=e=>{if(e.length<3)return e;let t=Ig,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},o_=(e,t)=>Math.max(2,Math.min(e,t-1)),s_=jg(),c_=(e,t,n)=>r=>Ru(e.get(Rg(t,r)),n).hex;function l_(e,t,n,r,i){let a=c_(e,t,i);return u_(n,e.dark).find(e=>!r.includes(a(e)))}function u_(e,t){let n=Ig,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return Ig.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const d_=(e,t)=>Math.floor(e*t),f_=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},p_=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},m_=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],h_=e=>typeof e==`string`&&m_.includes(e),g_={"van-der-corput":{place:p_,quantize:f_},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:d_},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:d_},monotonic:{place:(e,t)=>(e+.5)/t,quantize:d_},uniform:{place:()=>.5,quantize:f_}},__=e=>g_[e??`van-der-corput`];function v_(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function y_(e,t){let n=e[v_(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function b_(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const x_=(e,t)=>v_(t,e.hues.length);function S_(e,t,n,r){let{row:i,cell:a}=b_(n);return a===void 0?C_(e,t,i,a,r):w_(e,t,i,a,r)[a.index-a.lineStart]}function C_(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(x_(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>A_[e](n,r))?Jg:l;return{hue:u,shade:y_(i_(e,u,t.shade,i),r)}}function w_(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return T_(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:E_(n),E_(r,r.lineStart),i].join(`|`),()=>k_(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>C_(e,t,n,{...r,index:r.lineStart+o},i)),i))}const T_=jg();function E_({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${D_(r)},${i},${a}`}function D_(e){let t=O_.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const O_=new Map(m_.map(e=>[g_[e],e]));function k_(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&c_(e,n.hue,r)(n.shade)},o=V_(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=i_(e,s,t.shade,r),u=l.find(t=>!c.includes(c_(e,s,r)(t)))??l_(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const A_={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},j_=(e,t)=>e.get(Rg(t.hue,t.shade)),M_=4.5;function N_(e,t,n){return P_(e,`${t.hex}|${n}`,()=>{let r=Fu(t);return F_(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>ul(r,t)<ul(r,e)?t:e),t,n)})}const P_=jg();function F_(e,t,n,r){return I_(e,`${t.hex}|${n.hex}|${r}`,()=>Iu(t,n,M_,r))}const I_=jg(),L_=({decor:e,depth:t})=>qg(e.variation.open,t),R_=(e,t,n)=>i_(e,L_(t),t.decor.shade,n).map(e=>({hue:L_(t),shade:e}));function z_(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return B_(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=L_(t),c=t=>i_(e,t,o,n).map(c_(e,t,n)),l=a.keystones.length>0?[Jg]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(L_(t)),V_(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(c_(e,s,n)(o.activated))?l_(e,s,[o.activated],d,n)??o.activated:o.activated})}const B_=jg(),V_=(e,t,n)=>c_(e,L_(t),n)(z_(e,t,n)),H_=e=>({...e,depth:e.depth+1});function U_(e,t,n){return{state:e.get(Rg(L_(t),z_(e,t,n))),plane:e.get(`surface`),items:R_(e,t,n).map(t=>j_(e,t))}}function W_(e,t,n,r){return y_(U_(e,t,r).items,n)}function G_(e,t,n,r){let i=W_(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,L_(t),i,r)}}function K_(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&X_(e,t);case`band`:return t.kind===`band`&&Z_(e,t)}}const q_=Pg(Ng({index:Mg,count:Mg,distribution:Mg,axis:Mg,lineStart:Mg,lineEnd:Mg})),J_=Ng({variation:Mg,shade:Mg}),Y_=Ng({decor:J_,depth:Mg}),X_=Ng({kind:Mg,decor:J_,address:q_}),Z_=Ng({kind:Mg,band:Y_,address:q_}),Q_=e=>({kind:`bar`,decor:e,address:[]}),$_=(e,t)=>({...e,address:[...e.address,t]}),ev=e=>({kind:`band`,band:e,address:[]});function tv(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=S_(e,r,i,n),o=j_(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...G_(e,r,b_(i).cell,n),disclosure:H_(r)}}}}const nv=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function rv(e){let t=typeof e==`string`?nv.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const iv=`textual-dark`;function av(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function ov(){return xd()}function sv(){return[`bar`,...ov()]}let cv;function lv(e){return cv??=new Set(sv()),cv.has(e)}function uv(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return av(e===void 0?null:a(e),t,a(n??r),r,a)}const dv=[`style`,`palette`,`effect`];function fv(e){return e!==void 0&&e.includes(`{{`)}function pv(e,t,n,r,i){let a=fv(n)?{kind:`expression`,source:n}:i(n??r.name);return av(e===void 0?null:i(e),t,a,r,i)}const mv=`none`;function hv(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function gv(e,t){return hv(e,t)??hv(`none`,t)??{kind:`decided`,name:`none`,value:cu}}function _v(e,t,n,r){return pv(e,t,n,gv(mv,r),e=>hv(e,r))}const vv=`none`,yv={style:mv,palette:iv,effect:vv};function bv(e,t,n){return`${e} rendered "${yv[t]}": ${n}`}const xv=Object.freeze([vv,...Object.keys(Zh.loops)]),Sv=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),Cv=Object.keys(Sv),wv=Object.freeze([`bar`,...xv]);function Tv(e){let t=xv.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Ev(e){return Tv(e)??{kind:`decided`,name:`none`,value:`none`}}function Dv(e,t,n){return pv(e,t,n,Ev(vv),Tv)}const Ov=Object.freeze(Object.keys(Vm)),kv=[`powerline`,`capsule`,`plain`];function Av(e){return kv.includes(e)}const jv=[`truecolor`,`256`,`ansi`,`none`];function Mv(e){return jv.includes(e)}function Nv(e){return Cl(e)??H.DEFAULT}const Pv=Object.keys(t_),Fv=Object.keys(Kg),Iv=`true`,Lv=`false`,Rv=[Iv,Lv],zv={min:0,max:16};function Bv(e){return e===`true`?!0:e===`false`?!1:null}function Vv(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}function Hv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Uv(e){return ce(`sha256`).update(JSON.stringify(Wv(e))).digest(`hex`)}function Wv(e){return Array.isArray(e)?e.map(Wv):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,Wv(t)])):e}const Gv=[`vertical`,`horizontal`],Kv={vertical:`row`,horizontal:`cell`};function qv(e){return e.id??e.name}function Jv(e){return[...Zv(e)].flatMap(e=>e.kind===`segment`?[qv(e)]:[])}function Yv(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function Xv(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*Zv(e){yield e;for(let t of ty(e))yield*Zv(t)}const Qv=(e,t)=>`${e}.children[${t}]`,$v=e=>`${e}.opens.body`;function*ey(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*ey(r,Qv(t,n));else e.opens!==void 0&&(yield*ey(e.opens.body,$v(t)))}function ty(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function ny(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const ry=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function iy(e){return e.kind===`file`||e.kind===`shell`}function ay(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return iy(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function oy(e){let t=[];return ay(e,(e,n)=>(t.push([n,e]),e)),t}const sy=[`fail`,`ignore`];function cy(e){return e.missingData??`fail`}function*ly(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const uy=`theme`,dy=`effect`,fy=[uy,dy];function py(e){return{...e.settings,[uy]:{label:uy,domain:`theme`,default:e.palette??`bar`},[dy]:{label:dy,domain:wv,default:`bar`}}}function my(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function hy(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=my(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function gy(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&lv(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function _y(e){return String(e)}function vy(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Vv(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return gy(e,r)?r:void 0}function yy(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:vy(n,o))??i}function by(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const xy=[`left`,`center`,`right`],Sy=[`right`,`left`,`middle`];var Cy=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Ny(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},wy=class extends Cy{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
|
|
55
55
|
|
|
56
|
-
`)}},
|
|
57
|
-
`)),this.errors=e,this.name=`DroppedPlacements`}};function J(e,t){return
|
|
58
|
-
`)}function Iy(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 ${Vy(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Ly(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 ${Vy(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function Ry(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 ${Vy(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function zy(e,t,n){let r=Ry(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${av(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function By(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 ${Y(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function Vy(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Y(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Hy(e,t,n,r){return Wv(r)?(Ky(e,n,r,t.noun,new Set(Object.keys(t.fields)),Uy(e,t.removed??{},n,r)),Wy(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Vy(r)}`,line:J(e.source,n.split(`.`))}),null)}function Uy(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)qy(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Wy(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 Gy=new Set;function Ky(e,t,n,r,i,a=Gy){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 qy(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Jy(e,t,n,r){if(!Wv(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Vy(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 Yy(e,t,n,r){if(!Wv(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Vy(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 ${Vy(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 Ky(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Xy(e,t,n){return{json:ub(cb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Zy(e){return(...t)=>e()(...t)}function Qy(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 $y(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ry(e,t,r,n)}}function eb(){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 ${Vy(i)}`,line:J(e.source,[n])});return}return i}}}}function tb(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 ${Y(o)}`,line:J(e.source,[i])});return}return o}}}}function nb(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 ${Y(a)}`,line:J(e.source,[r])});return}return a}}}}function rb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>zy(e,t,r)}}function ib(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Iy(e,t,r,n)??void 0}}function ab(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function ob(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Iy(e,t,r,n);if(i===null)return;let a=ab(`${t}.${n}`,i);return a===null?i:qy(e,`${t}.${n}`,a)??void 0}}}function sb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>By(t,n,i,r,e)}}function cb(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function lb(e){return cb(e.fields)}function ub(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function db(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function fb(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const pb=[`claude`,`tmux`],mb=`ne .tmux.pane ""`,hb={band:{switch:{setting:`experimentalBand`,on:!0,inTmux:!1},label:`🧪 band (A)`,handsOff:!0,rows:null},statusline:{switch:{setting:`experimentalStatusline`,on:!0,inTmux:!1},label:`🧪 statusline (B)`,handsOff:!1,rows:null},pane:{switch:{setting:`experimentalPane`,on:!0,inTmux:!1},label:`🧪 tmux pane (C)`,handsOff:!0,rows:null},tmuxStatus:{switch:{setting:`renderer`,on:`tmux`,inTmux:!0},label:`tmux status line`,handsOff:!0,rows:5}},gb=Object.keys(hb),_b=gb.filter(e=>hb[e].switch.on===!0),vb={by:`request`},yb=e=>`drawing.${e}`,bb={subscribers:0,fps:0,shown:!0},xb=(e,t)=>`feeds.${e}.${t}`;function Sb(e){return Object.fromEntries(gb.map(t=>[t,e(t)]))}const Cb=Sb(()=>bb);function wb(e){return typeof e==`string`&&Object.hasOwn(hb,e)?e:null}const Tb=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),Eb=[...Tb(3,1),...Tb(3,.25)],Db=Eb.reduce((e,{seconds:t})=>e+t,0),Ob={min:15,max:600,step:15},kb=(e,t)=>e+t,Ab=e=>e-Db,jb=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),Mb=(e,t,n={})=>({spec:sb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),Nb=e=>t=>e.includes(t)?`🧪 ${t}`:t,Pb={spec:eb(),domain:`bool`,parse:Hv},Fb=e=>({spec:tb(e),domain:e,parse:t=>Uv(t,e)});function Ib(e,t,n,r={}){return{kind:`session`,...Mb(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function Lb(e,t){return{kind:`session`,...Pb,floor:e,control:t,themeDefault:!1}}function Rb(e,t,n){return{kind:`session`,...Fb(e),floor:t,control:n,themeDefault:!1}}function zb(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const Bb=e=>({kind:`text`,spec:e}),Vb={required:!1,json:{enum:[...Nv]},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: ${Nv.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return By(e,t,r,n,Nv)}},Hb={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Ry(e,t,r,n);return mv(i)?i:zy(e,t,r)}},Ub={required:!1,json:{anyOf:[{enum:[...Cv]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&mv(i)?i:By(e,t,r,n,Cv)}},Wb=/^[^\r\n]*\S[^\r\n]*$/u,Gb=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Kb={required:!1,json:{type:`string`,pattern:Wb.source,not:{pattern:Gb.source}},parse:(e,t,n,r)=>{let i=Ry(e,t,r,n);if(i===void 0||Wb.test(i)&&!Gb.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])})}},qb=Object.fromEntries(_b.map(e=>[hb[e].switch.setting,Lb(!1,jb(hb[e].label,`toggles`))])),Jb={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Yb={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Jb[e]})},Xb={palette:zb(`theme`,Hb,{themes:`themes`},jb(`🎨 theme`,`door`)),preset:zb(`preset`,$y(),{from:`presets`},jb(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:zb(`style`,$y(),{from:`styles`},jb(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:zb(`effect`,Ub,{from:Cv},jb(`✨ effect`,`look`)),endcaps:Ib(Av,`powerline`,jb(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:Ib(Iv,`accent`,jb(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:Nb(i_),themeDefault:!0}),shade:Ib(Lv,`middle`,jb(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:Nb(qg),themeDefault:!0}),transitions:Lb(!1,jb(`fade in/out`,`look`)),animationSpeed:Ib(Tv,`1x`,jb(`speed`,`look`)),autoWrap:Lb(!0,jb(`wrap`,`config`)),padding:Rb({...Vv,step:1},1,jb(`padding`,`config`)),updateNotice:Lb(!0,jb(`update notice`,`config`)),menuTimeout:Rb(Ob,120,jb(`menu timeout`,`config`)),renderer:Ib(pb,`claude`,jb(`renderer`,`config`,{shown:mb}),{optionDomain:`renderers`,library:Yb}),...qb,colorCompatibility:{kind:`config`,...Mb(Nv,`colorCompatibilities`),spec:Vb,floor:`truecolor`},default_empty_value:Bb($y()),default_separator:Bb($y()),menuGlyph:Bb(Kb)},Zb=Object.entries(Xb),Qb=Zb.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),$b=Zb.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),ex=Zb.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),gte=Zb.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function tx(e){return Xb[e]}const nx=e=>tx(e).floor;function rx(e){let t=Xb[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const ix=e=>`${e}.effective`,_te=e=>{let t=Xb[e];return t.kind===`selection`?t.sessionKey:e},ax=Object.fromEntries($b.map(e=>{let t=_te(e);return[t,{configKey:e,sessionKey:t,effectiveVar:ix(t),...Xb[e].control}]})),ox=Object.keys(ax),sx=Object.values(ax),cx=Qb.filter(e=>Xb[e].kind===`config`).map(e=>({configKey:e,effectiveVar:ix(e)})),vte=new Set(cx.map(e=>e.configKey)),lx=new Map([...sx,...cx].map(e=>[e.configKey,e.effectiveVar])),ux=new Map(sx.map(e=>[e.sessionKey,e.effectiveVar]));function dx(e){return Object.fromEntries(ox.map(t=>[t,e(t)]))}const fx=new Map(ox.map(e=>[ax[e].sessionKey,e])),px=new Map;function mx(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 hx(e,t){return e===`bar`?t:mx(e)}function gx(e){let t=px.get(e);if(t!==void 0)return t;let n=xee(e);return n===null?null:(px.set(e,n),n)}function _x(e,t){return yte(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Aee(e,t))}const yte=Ng();function vx(e){let t=gx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function yx(e,t,n){let r=vx(e);return r===null?(n(Sv(t,`palette`,`"${e}" names no installed theme${av(e)}`)),bx()):r}function bte(e,t,n){return hv(e,t,n,bx(),vx)}function bx(){return{kind:`decided`,name:ov,value:mx(ov)}}const xx=/^[A-Za-z_][A-Za-z0-9_]*$/;function xte(e){return`#${e+1}`}const Sx={rows:{}};function Cx(e){return`rows`in e}function wx(e){return Object.fromEntries(e.map((e,t)=>[xte(t),e]))}function Ste(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:wx(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:wx([n])}}function Tx(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Ex(e){return Cx(e)?Tx(e):e}function*Dx(e,t){if(!Cx(e)){yield*ny(e,t);return}yield[Tx(e),t];for(let[n,r]of Object.entries(e.rows))yield*ny(r,`${t}.rows.${n}`)}function Ox(e,t){return Cx(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Ste(e)}function kx(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...$v(Tx(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||Yv(e)===t.id)))return e;let i=r.find(e=>Yv(e)===n);if(i!==void 0)return Ax(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,Cte(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]))}}:Ax(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function Ax(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function Cte(e,t,n,r){if(e.kind===`segment`&&Yv(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`?jx(e,t,n,r):Mx(e,t,n,r)}function jx(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&Yv(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`?jx(a,t,n,r):Mx(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function Mx(e,t,n,r){let i=!1,a=Qv(e,e=>{let a=jx(e,t,n,r);return i=a!==null,a??e});return i?a:null}function Nx(e){if(!Cx(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Px=`default`,wte={};function Fx(e){return[...new Set([Px,...Object.keys(e)])]}function Ix(e,t,n){return fv(void 0,e,t,Px,n)}function Lx(e,t){let n={[Px]:wte,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Px}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Rx(e,t){let n=Lx(e.presets,t).root??Sx;return{node:Tx(Ox(n,e.root)),path:Nx(n)?`presets.${t}.root`:`root`}}function Tte(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=kx(e.root,t),i=Object.entries(e.presets).filter(([,e])=>Nx(e.root??Sx)).map(([n,r])=>({name:n,preset:r,...kx(Ox(r.root??Sx,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:Tx(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>zx(e,`${t} (in ${n.join(`, `)})`)))}}function zx(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function Bx(e,t){return{...e.globals,...Lx(e.presets,t).globals}}const Vx=new Map;function Hx(e,t,n={}){Vx.set(e,{permanent:!0,resolve:t,...n})}Hx(`themes`,()=>cv(),{paletteOf:e=>mx(e)});const Ux=`placementThemes`;Hx(Ux,lv,{paletteOf:(e,t)=>hx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of gte)Hx(e,()=>t,{library:n,labelOf:r});function Ete(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>_x(n.basePalette,e.styles[t])}],[`presets`,{members:Fx(e.presets)}]])}function Wx(e){return[...new Set([...Vx.keys(),...e.keys()])]}function Gx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=Vx.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(Kx(e,t))}const Dte=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function Kx(e,t){let n=Dte.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Wx(t).join(`, `)})`}const qx=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function Jx(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*Yx(e){let t=[];Xx(e,(e,n)=>(t.push([n,e]),e)),yield*t}function Xx(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 Ote(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const Zx=`groups.`,Qx=`menus.`,$x=`menupages.`,eS=`edit.`,tS=`candybar.`,nS=[Zx,Qx,$x,eS,tS];function rS(e){return nS.some(t=>e.startsWith(t))}const iS=`${tS}menu`,aS=ta,oS={variable:iS,key:iS,member:aS},sS=`${tS}diagnostics`,cS=`${Zi}://`,lS=`dispatch`,uS=`set-state`,dS=`step-state`,fS=`copy-text`,pS=`open-in-vscode`,mS=`toolbar-toggle`,hS=`set-config`,gS=`step-config`,_S=`save`,vS=`save-preset`,yS=`save-theme-default`,bS=`delete-preset`,xS=`reset-config`,SS=`apply-layout-op`,CS=`undo`,wS=`redo`,TS=`back`,ES=`rewind`,DS=`apply-update`,OS=`doctor-run`,kS=`doctor-fix`,AS=`doctor-mark`,jS=`probe`,MS=`slash`,NS=`repo-config`,PS=`copy-diagnostic`,FS=`range`,IS=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,LS=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function RS(e,t){if(e===sS)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!rS(e))return n;let r=LS(LS(e,$x),Qx);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 zS(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const BS={[uS]:([,...e])=>e.flatMap((t,n)=>n%2==0?[RS(t,e[n+1])]:[]),[dS]:([,e,t])=>[IS(e,t)],[fS]:([,e])=>[`copy ${zS(e)}`],[pS]:([,e])=>[`open ${e} in vs code`],[mS]:()=>[`toggle the toolbar`],[hS]:([,e,t])=>[`save ${e} as ${t}`],[gS]:([,e,t])=>[`save ${IS(e,t)}`],[_S]:()=>[`save settings`],[vS]:()=>[`save as a new preset`],[yS]:()=>[`save this look for the theme`],[bS]:([,e])=>[`delete preset ${e}`],[xS]:([,...e])=>e.map(e=>`reset ${e}`),[SS]:([,e,t])=>[`edit ${t} in ${e}`],[CS]:()=>[`undo`],[wS]:()=>[`redo`],[TS]:()=>[`go back`],[ES]:()=>[`cancel edits`],[DS]:()=>[`update cc-candybar`],[OS]:()=>[`run doctor`],[kS]:([,e])=>[`fix ${e}`],[AS]:([,e,t])=>[`mark ${e} ${t}`],[MS]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[NS]:([,e,t])=>[`mark config in ${e} ${t}`],[PS]:()=>[`copy diagnostic`]},VS=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function HS(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=>BS[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function US(e){return e.map(encodeURIComponent).join(`/`)}function WS(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function GS(e,t,n=HS(t)){let r=t.map(e=>`e=${encodeURIComponent(`${e.verb}/${US(e.args)}`)}`);return qS(e,lS,[`does=${VS(n)}`,...r].join(`&`))}function KS(e,t){return qS(e,jS,encodeURIComponent(t))}function qS(e,t,n){return`${cS}to/${e}/${t}/${n}`}function JS(e){return new r(e).getAll(`e`).map(QS)}const YS=new Set([uS,xS]);function XS(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&ZS(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function ZS(e,t){if(e.verb!==t.verb||!YS.has(e.verb))return;let[n,r]=[QS(e.value),QS(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function QS(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function $S(e){if(!e.startsWith(cS))return{ok:!1,problem:`expected a ${cS} link, got: ${e}`};let t=e.slice(cS.length);if(!t.startsWith(`to/`))return{ok:!1,problem:`the link is in ${t.includes(`/`)?`the direct verb form ${cS}<verb>/…`:`the bare copy form ${cS}<value>`}, which names no renderer: ${e}`};let n=t.slice(3),r=n.indexOf(`/`);if(r===-1)return{ok:!1,problem:`the link names a renderer and no click: ${e}`};try{return tC(n.slice(r+1),We(n.slice(0,r)))}catch(e){return{ok:!1,problem:e.message}}}function eC(e){if(!$i(e))return!1;let t=e.slice(cS.length).split(`%`)[0];return!t.startsWith(`to/`)&&!`to/`.startsWith(t)}function tC(e,t){let n=e.indexOf(`/`);if(n===-1)return{ok:!1,problem:`the link carries no verb: ${e}`};let r=e.slice(0,n);try{return{ok:!0,to:t,verb:decodeURIComponent(r),value:e.slice(n+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${r}`}}}const nC=[`plugins`,`repo`];function rC({scope:e,name:t}){return`${e}.${t}`}function iC(e){return t=>t===e||t.startsWith(`${e}.`)}const aC=`self`;function oC(e){return nC.find(t=>e===t||e.startsWith(`${t}.`))}function sC(e,t){let n=oC(e);if(n===void 0||n===e)return``;let r=nC.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 cC=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*lC(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 uC=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,dC=RegExp(`^(?:(\\$)(?:\\.(${uC}))?|\\.(${uC})?)(?=[\\s)]|$)`);function fC(e,t,n){let r=dC.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 pC=/^(\w+)\b\s*([\s\S]*)$/;function*mC(e,t){let n=[t];for(let r of lC(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=pC.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:fC(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(fC(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const hC=/(?<![.$])\btemplate\s+$/;function*gC(e,t,n){let r=0;for(let i of[...e.matchAll(cC)]){let a=i.index+i[0].length;hC.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:fC(e.slice(a),t,n),index:i.index}),r=a}}function*_C(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...mC(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...gC(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 vC(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const yC=new WeakMap;function bC(e,t){let n=yC.get(t);return n===void 0&&(n=vC(e=>[..._C(e,t)]),yC.set(t,n)),n(e)}const xC=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${uC})`,`g`);function*SC({code:e,dot:t,root:n}){let r=e.replace(cC,``);for(let e of[...r.matchAll(xC)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function CC(e,t){let n=new Map;for(let r of bC(e,t))for(let e of SC(r))n.has(e)||n.set(e,r.via);return n}const wC=/(?<![.$])\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*EC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(cC)]){let a=e.slice(t,i.index),o=wC.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 DC(e,t){let n=new Map;for(let{code:r,via:i}of bC(e,t))for(let{name:e,site:t}of EC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function OC(e,t){let n=new Map;for(let{code:r,via:i}of bC(e,t))for(let e of r.matchAll(cC)){let t=e[0].slice(1,-1);if(!eC(t))continue;let r=`${t}\0${i??`\0`}`;n.has(r)||n.set(r,{literal:t,via:i})}return[...n.values()]}const kC=e=>Object.keys(TC).filter(t=>TC[t]>=e).join(`|`),AC=RegExp(`(?<![\\w.$])(?:(?:${kC(1)})\\s+|(?:${kC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function jC(e,t){for(let{code:n}of bC(e,t))if(AC.test(n.replace(cC,`""`)))return!0;return!1}const MC=/(?<![\w.$])[A-Za-z_]\w*/g;function NC(e,t){let n=new Set;for(let{code:r}of bC(e,t))for(let[e]of r.replace(cC,``).matchAll(MC))n.add(e);return n}function PC(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 bC(e,t))for(let{name:e}of gC(r,i,a))n.add(e);return n}const IC=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function LC(e,t,n){let r=IC(t),i=iC(t),a=[];for(let{dot:t,block:n}of mC(e,``)){let e=n.text.replace(cC,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[...gC(n.text,t,``),...EC(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*RC(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*zC(e){for(let[t,n]of RC(e))yield[t,n]}function BC(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 BC(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function HC(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),UC(r)&&n.add(e)};for(let[t,n]of zC(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function UC(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&iy(e.parse)===`json`}var WC=De((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Lt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return he(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function w(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:he(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function T(e,t){return{t:e,i:t,o:E,u:ee}}function E(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,te(e,0,0,n,!1,!1)),2)}function ee(e,t,n,r){let i=te(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function D(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 te(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 O(e,t){return{t:e,i:t,o:k,u:ne}}function k(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ne(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function A(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 re(e,t){return{t:e,i:t,o:ie,u:ae}}function ie(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ae(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function oe(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 se(e){return{t:Jt,i:e,o:ce,u:le}}function ce(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:he(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 le(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:he(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 ue(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function de(e){return e||Xt}function fe(e){return ue(e,oe)}function pe(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 me(e){return ue(e,A)}function he(e,t,n=!1,r){function i(){return ge(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ge(e,t,n,r,i){let a=_e(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{ve(a)}}function _e(e,t){let n=N.trackingDerivation,r=!t||!n;je();let i=N.allowStateChanges;r&&Te();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 ve(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Me(),e.R&&Ee(e.k),N.suppressReactionErrors=!1}function ye(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 be(e){return e instanceof xn}function xe(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Te(),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 Ee(t),!0}if(e.K===2)return Ee(t),!0}}return De(e),Ee(t),!1}}}function Se(e,t,n){De(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&&ke(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Oe(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ce(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)ke(t[n],e);e.K=-1}function we(e){let t=Te();try{return e()}finally{Ee(t)}}function Te(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Ee(e){N.trackingDerivation=e}function De(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Oe(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function ke(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ae(e))}function Ae(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function je(){N.inBatch++}function Me(){--N.inBatch===0&&(Ie(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ne(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ne))}function Pe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ae(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 Fe(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Re(e){return ue(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?he(t.name||`<unnamed action>`,t,e):r(n)?he(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ge(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=Te();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Ee(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){je();try{return e.apply(t)}finally{Me()}}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=he(`When-effect`,t);var a=He(t=>{ye(!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=Te();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{Ee(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=Te(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ee(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]=se({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=Te();je();try{return e()}finally{Me(),Ee(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 Pe(this)}reportChanged(){je(),Fe(this),Me()}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=se(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=re(`observable`),Qt=re(`observable.ref`,{A:y}),$t=re(`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=re(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=de(t);return new _n(e,pe(n),n.name,!0,n.equals)},array(e,t){let n=de(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,pe(n),n.name)},map(e,t){let n=de(t);return new rr(e,pe(n),n.name)},set(e,t){let n=de(t);return new or(e,pe(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=fe(Qt),rn=fe($t),an=fe(Zt),on=fe(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?oe(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=O(cn),un=me(O(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return A(ln,e,t);if(o(e))return me(O(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=he(`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(Pe(this),xe(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(Ne)}else xe(this)&&(this.Nt(),je(),this.rt=this.Rt(!1),Me());let e=this.rt;if(be(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||be(e)||be(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Se(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||(Ce(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),Ie())}X(){if(!this.isDisposed){je(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,xe(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Me()}}track(e){if(this.isDisposed)return;je(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Se(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ce(this),be(n)&&this.Pt(n.cause),Me()}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||(je(),Ce(this),Me()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return D(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=ue(Wn,D),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(()=>{we(()=>{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(()=>{we(()=>{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{je();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{Me()}return!0}S(e,t,n,r=!1){try{je();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{Me()}return!0}m(e,t,n=!1){try{je();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{Me()}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;je();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),Fe(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{Me()}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=ye,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=ve,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=_e,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=ye(!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)){je();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Me()}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),je(),r>=n.length&&(n.length=r+1),n[r]=i,Me()):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=we,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||{})}})),GC=De((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=D(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function E(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ee(e){return e===null?null:typeof e==`object`?``+e:e}function D(e,t){return o.hasOwnProperty.call(e,t)}let te=Object.getOwnPropertyDescriptors;function O(e,t){return!!(e&t)}function k(e,t,n){return n?e|=t:e&=~t,e}function ne(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let A=Symbol(`mobx administration`);var re=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 O(this.flags_,1)}set isBeingObserved(e){this.flags_=k(this.flags_,1,e)}get isPendingUnobservation(){return O(this.flags_,2)}set isPendingUnobservation(e){this.flags_=k(this.flags_,2,e)}get diffValue(){return+!!O(this.flags_,4)}set diffValue(e){this.flags_=k(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 ie=b(`Atom`,re);function ae(e,t=f,n=f){let r=new re(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function oe(e,t){return e===t}function se(e,t){return Li(e,t)}function ce(e,t){return Li(e,t,1)}let le=Object.is;function ue(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 de(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 fe(e){return e}function pe(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let me=`override`,he={annotationType_:me,make_:_e,extend_:ve};function ge(e){return e.annotationType_===me}function _e(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),D(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function ve(e,t,r,i){n(44,this.annotationType_)}function ye(e,t){return{annotationType_:e,options_:t,make_:be,extend_:xe}}function be(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,we(e,this,t,n,!1)),2)}function xe(e,t,n,r){let i=we(e,this,t,n);return e.defineProperty_(t,i,r)}function Se(e,t,r){ne(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 Ce(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 we(e,t,n,r,i=M.safeDescriptors){var a,o;Ce(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 Te(e,t){return{annotationType_:e,options_:t,make_:Ee,extend_:De}}function Ee(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&&(!D(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ae(e,this,t,n,!1,!1)),2)}function De(e,t,n,r){let i=Ae(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Oe(e,t,n){var r;ne(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 ke(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 Ae(e,t,n,r,i,a=M.safeDescriptors){ke(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 je(e,t){return{annotationType_:e,options_:t,make_:Me,extend_:Ne}}function Me(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ne(e,t,n,i){return Fe(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Pe(e,t,n){ne(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)[A],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[A],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 Fe(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??ue,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)}\``);ne(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Ei(e)[A];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??ue,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[A]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[A]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?ot:ut;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ot:ut).extend_(e,t,n,r))}function qe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:fe}),Qe=Ie(`observable.shallow`,{enhancer_:de}),$e=Ie(`observable.struct`,{enhancer_:pe});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?ue:e.deep===!1?fe:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??ue:ue}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 Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Pe)}let pt=je(dt),mt=ft(je(`computed.struct`,{equals:se})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Pe(pt,e,t);if(g(e))return ft(je(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 re{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=le){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 ee(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||le,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 O(this.flags_,1)}set isComputing(e){this.flags_=k(this.flags_,1,e)}get isRunningSetter(){return O(this.flags_,2)}set isRunningSetter(e){this.flags_=k(this.flags_,2,e)}get isBeingObserved(){return O(this.flags_,4)}set isBeingObserved(e){this.flags_=k(this.flags_,4,e)}get isPendingUnobservation(){return O(this.flags_,8)}set isPendingUnobservation(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(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 ee(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 O(this.flags_,1)}set isDisposed(e){this.flags_=k(this.flags_,1,e)}get isScheduled(){return O(this.flags_,2)}set isScheduled(e){this.flags_=k(this.flags_,2,e)}get isTrackPending(){return O(this.flags_,4)}set isTrackPending(e){this.flags_=k(this.flags_,4,e)}get isRunning(){return O(this.flags_,8)}set isRunning(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(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[A]=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=ye(N),kn=ye(`action.bound`,{bound:!0}),An=ye(En,{autoAction:!0}),jn=ye(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,Se)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Se(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(ye(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||le,_=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=te(t);return Fi(()=>{let t=Ei(e,i)[A];T(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,Oe)}let or=Te(`flow`),sr=Te(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Oe(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[A];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[A];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[A]||ie(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[A].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[A].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[A].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[A].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[A].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[A].defineProperty_(t,r);n(39)}function jr(e){if(ki(e))return e[A].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[A].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[A]}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[A]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Jr(e,t){let r=Ht();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Ei(e,n)[A];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Ei(e,r)[A];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(A),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[A];return t===A?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):D(si,t)?si[t]:e[t]},set(e,t,n){let r=e[A];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 re(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Ft(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,A,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[A];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];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[A].spliceWithArray_(e,t,n)},push(...e){let t=this[A];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[A].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];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[A],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[A];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[A];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[A];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[A])}let mi={},hi=`delete`;var gi=class{constructor(e,t=ue,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[A]=mi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=ae(`${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),fe,`${this.name_}.${E(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_}.${E(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)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=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`,Vi(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=ue,n=`ObservableSet@`+u()){this.name_=void 0,this[A]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=ae(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`,Vi(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 re(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!D(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return D(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_,fe,`${this.name_}.${E(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_),!D(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(),T(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.`),D(e,A))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,A,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[A].getObservablePropValue_(e)},set(t){return this[A].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[A]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ge(t)&&D(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[A].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[A],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ie(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[A]))return e[A];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(ie(e)||At(e)||vn(e)||P(e)||xi(e))return e;if(e[A])return e[A];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 Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(D(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||xi(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:A}),e.$mobx=A,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=le,e.compareIdentity=oe,e.compareShallow=ce,e.compareStructural=se,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=ae,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=he,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),X=De(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=WC():t.exports=GC()}))();function KC(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(KC);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(KC)}default:return!1}}function qC(e){if(Array.isArray(e))return Object.freeze(e.map(qC));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]=qC(r);return Object.freeze(t)}return e}function JC(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 YC(e){return typeof e==`string`?e:String(e)}function XC(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 ZC(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 QC=class extends Error{constructor(e,t){super(t),this.variable=e}};function $C(e){return e instanceof QC?e:e instanceof Error&&e.cause!==void 0?$C(e.cause):void 0}const ew=e=>co(e);var tw=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,ew(n)||dw(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=ew(n)?null:r.now()}read(){let e=this.cell.get();if(ew(e))throw new QC(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){ew(e)||dw(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},nw=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},rw=class{constructor(e){this.deriver=e}read(){return this.deriver()}},iw=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new nw(`Variable "${e}"`,()=>{let e=n();return dw(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},aw=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new rw(()=>{let e=n();return dw(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},ow=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(uw(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=uw(e);lw(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},sw=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new nw(`Variable "${e}"`,()=>uw(t()),lw)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function cw(e){return JSON.stringify(e)}function lw(e,t){return cw(e)===cw(t)}function uw(e){return e.kind===`ok`?{kind:`ok`,value:qC(e.value)}:e}function dw(e,t,n,r){let i=JC(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var fw=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new tw(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new ow(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new sw(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`?iw:aw;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new rw(n);let r=new nw(`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 ow))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?e:F(cw(e))}try{return F(String(t.read()))}catch(e){return $C(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):so(`unread`)}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof iw||t instanceof sw)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}},pw=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?Sw(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}},mw=class extends pw{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},hw=class extends pw{name=`EvalError`;kind=`EvalError`},gw=class extends hw{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Cw(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}},_w=class extends hw{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}},vw=class extends hw{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}},yw=class extends vw{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)}`}},bw=class extends hw{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},xw=class extends hw{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Sw(e,t){let n=e.split(`
|
|
56
|
+
`)}},Ty=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
|
|
57
|
+
`)),this.errors=e,this.name=`DroppedPlacements`}};function J(e,t){return Ey(e)(t)}function Ey(e){let t,n=()=>(t??={node:Dy(e)},t.node);return t=>Oy(e,n,t)}function Dy(e){try{return wa(e)}catch(e){if(e instanceof ba)return;throw e}}function Oy(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?ky(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=Ay(e,i,t);if(n===-1)return a===void 0?void 0:jy(e,a);i=n,a=n}return a===void 0?void 0:jy(e,a)}function ky(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:Ta(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:jy(e,i.span.start)}function Ay(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 jy(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function My(e,t){try{return wa(t),null}catch(n){if(!(n instanceof ba))throw n;return`${e}:${jy(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Ny(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 Py(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 ${zy(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Fy(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 ${zy(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function Iy(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 ${zy(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function Ly(e,t,n){let r=Iy(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${rv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function Ry(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 ${Y(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function zy(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Y(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function By(e,t,n,r){return Hv(r)?(Wy(e,n,r,t.noun,new Set(Object.keys(t.fields)),Vy(e,t.removed??{},n,r)),Hy(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${zy(r)}`,line:J(e.source,n.split(`.`))}),null)}function Vy(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Gy(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Hy(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 Uy=new Set;function Wy(e,t,n,r,i,a=Uy){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 Gy(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Ky(e,t,n,r){if(!Hv(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${zy(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 qy(e,t,n,r){if(!Hv(r))return e.issues.push({path:n,message:`${n} must be an object, got ${zy(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 ${zy(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 Wy(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Jy(e,t,n){return{json:cb(ob(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Yy(e){return(...t)=>e()(...t)}function Xy(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 Zy(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Iy(e,t,r,n)}}function Qy(){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 ${zy(i)}`,line:J(e.source,[n])});return}return i}}}}function $y(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Y(o)}`,line:J(e.source,[i])});return}return o}}}}function eb(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 ${Y(a)}`,line:J(e.source,[r])});return}return a}}}}function tb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ly(e,t,r)}}function nb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Py(e,t,r,n)??void 0}}function rb(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function ib(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Py(e,t,r,n);if(i===null)return;let a=rb(`${t}.${n}`,i);return a===null?i:Gy(e,`${t}.${n}`,a)??void 0}}}function ab(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Ry(t,n,i,r,e)}}function ob(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 sb(e){return ob(e.fields)}function cb(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function lb(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function ub(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const db=[`claude`,`tmux`],fb=`ne .tmux.pane ""`,pb={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}},mb=Object.keys(pb),hb=mb.filter(e=>pb[e].switch.on===!0),gb={by:`request`},_b=e=>`drawing.${e}`,vb={subscribers:0,fps:0,shown:!0},yb=(e,t)=>`feeds.${e}.${t}`;function bb(e){return Object.fromEntries(mb.map(t=>[t,e(t)]))}const xb=bb(()=>vb);function Sb(e){return typeof e==`string`&&Object.hasOwn(pb,e)?e:null}const Cb=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),wb=[...Cb(3,1),...Cb(3,.25)],Tb=wb.reduce((e,{seconds:t})=>e+t,0),Eb={min:15,max:600,step:15},Db=(e,t)=>e+t,Ob=e=>e-Tb,kb=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),Ab=(e,t,n={})=>({spec:ab(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),jb=e=>t=>e.includes(t)?`🧪 ${t}`:t,Mb={spec:Qy(),domain:`bool`,parse:Bv},Nb=e=>({spec:$y(e),domain:e,parse:t=>Vv(t,e)});function Pb(e,t,n,r={}){return{kind:`session`,...Ab(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function Fb(e,t){return{kind:`session`,...Mb,floor:e,control:t,themeDefault:!1}}function Ib(e,t,n){return{kind:`session`,...Nb(e),floor:t,control:n,themeDefault:!1}}function Lb(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const Rb=e=>({kind:`text`,spec:e}),zb={required:!1,json:{enum:[...jv]},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: ${jv.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return Ry(e,t,r,n,jv)}},Bb={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Iy(e,t,r,n);return fv(i)?i:Ly(e,t,r)}},Vb={required:!1,json:{anyOf:[{enum:[...xv]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&fv(i)?i:Ry(e,t,r,n,xv)}},Hb=/^[^\r\n]*\S[^\r\n]*$/u,Ub=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Wb={required:!1,json:{type:`string`,pattern:Hb.source,not:{pattern:Ub.source}},parse:(e,t,n,r)=>{let i=Iy(e,t,r,n);if(i===void 0||Hb.test(i)&&!Ub.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])})}},Gb=Object.fromEntries(hb.map(e=>[pb[e].switch.setting,Fb(!1,kb(pb[e].label,`toggles`))])),Kb={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},qb={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Kb[e]})},Jb={palette:Lb(`theme`,Bb,{themes:`themes`},kb(`🎨 theme`,`door`)),preset:Lb(`preset`,Zy(),{from:`presets`},kb(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:Lb(`style`,Zy(),{from:`styles`},kb(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:Lb(`effect`,Vb,{from:xv},kb(`✨ effect`,`look`)),endcaps:Pb(Ov,`powerline`,kb(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:Pb(Pv,`accent`,kb(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:jb(n_),themeDefault:!0}),shade:Pb(Fv,`middle`,kb(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:jb(Gg),themeDefault:!0}),transitions:Fb(!1,kb(`fade in/out`,`look`)),animationSpeed:Pb(Cv,`1x`,kb(`speed`,`look`)),autoWrap:Fb(!0,kb(`wrap`,`config`)),padding:Ib({...zv,step:1},1,kb(`padding`,`config`)),updateNotice:Fb(!0,kb(`update notice`,`config`)),menuTimeout:Ib(Eb,120,kb(`menu timeout`,`config`)),renderer:Pb(db,`claude`,kb(`renderer`,`config`,{shown:fb}),{optionDomain:`renderers`,library:qb}),...Gb,colorCompatibility:{kind:`config`,...Ab(jv,`colorCompatibilities`),spec:zb,floor:`truecolor`},default_empty_value:Rb(Zy()),default_separator:Rb(Zy()),menuGlyph:Rb(Wb)},Yb=Object.entries(Jb),Xb=Yb.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),vte=Yb.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Zb=Yb.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),yte=Yb.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Qb(e){return Jb[e]}const $b=e=>Qb(e).floor;function ex(e){let t=Jb[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const tx=e=>`${e}.effective`,bte=e=>{let t=Jb[e];return t.kind===`selection`?t.sessionKey:e},nx=Object.fromEntries(vte.map(e=>{let t=bte(e);return[t,{configKey:e,sessionKey:t,effectiveVar:tx(t),...Jb[e].control}]})),rx=Object.keys(nx),ix=Object.values(nx),ax=Xb.filter(e=>Jb[e].kind===`config`).map(e=>({configKey:e,effectiveVar:tx(e)})),xte=new Set(ax.map(e=>e.configKey)),ox=new Map([...ix,...ax].map(e=>[e.configKey,e.effectiveVar])),sx=new Map(ix.map(e=>[e.sessionKey,e.effectiveVar]));function cx(e){return Object.fromEntries(rx.map(t=>[t,e(t)]))}const lx=new Map(rx.map(e=>[nx[e].sessionKey,e])),ux=new Map;function dx(e){let t=px(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 fx(e,t){return e===`bar`?t:dx(e)}function px(e){let t=ux.get(e);if(t!==void 0)return t;let n=xee(e);return n===null?null:(ux.set(e,n),n)}function mx(e,t){return Ste(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Aee(e,t))}const Ste=jg();function hx(e){let t=px(e);return t===null?null:{kind:`decided`,name:e,value:t}}function gx(e,t,n){let r=hx(e);return r===null?(n(bv(t,`palette`,`"${e}" names no installed theme${rv(e)}`)),_x()):r}function Cte(e,t,n){return pv(e,t,n,_x(),hx)}function _x(){return{kind:`decided`,name:iv,value:dx(iv)}}const vx=/^[A-Za-z_][A-Za-z0-9_]*$/;function wte(e){return`#${e+1}`}const yx={rows:{}};function bx(e){return`rows`in e}function xx(e){return Object.fromEntries(e.map((e,t)=>[wte(t),e]))}function Tte(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:xx(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:xx([n])}}function Sx(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Cx(e){return bx(e)?Sx(e):e}function*wx(e,t){if(!bx(e)){yield*ey(e,t);return}yield[Sx(e),t];for(let[n,r]of Object.entries(e.rows))yield*ey(r,`${t}.rows.${n}`)}function Tx(e,t){return bx(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Tte(e)}function Ex(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...Zv(Sx(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||qv(e)===t.id)))return e;let i=r.find(e=>qv(e)===n);if(i!==void 0)return Dx(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,Ete(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]))}}:Dx(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function Dx(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function Ete(e,t,n,r){if(e.kind===`segment`&&qv(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`?Ox(e,t,n,r):kx(e,t,n,r)}function Ox(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&qv(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`?Ox(a,t,n,r):kx(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function kx(e,t,n,r){let i=!1,a=Xv(e,e=>{let a=Ox(e,t,n,r);return i=a!==null,a??e});return i?a:null}function Ax(e){if(!bx(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const jx=`default`,Dte={};function Mx(e){return[...new Set([jx,...Object.keys(e)])]}function Nx(e,t,n){return uv(void 0,e,t,jx,n)}function Px(e,t){let n={[jx]:Dte,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${jx}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Fx(e,t){let n=Px(e.presets,t).root??yx;return{node:Sx(Tx(n,e.root)),path:Ax(n)?`presets.${t}.root`:`root`}}function Ote(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=Ex(e.root,t),i=Object.entries(e.presets).filter(([,e])=>Ax(e.root??yx)).map(([n,r])=>({name:n,preset:r,...Ex(Tx(r.root??yx,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:Sx(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>Ix(e,`${t} (in ${n.join(`, `)})`)))}}function Ix(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function Lx(e,t){return{...e.globals,...Px(e.presets,t).globals}}const Rx=new Map;function zx(e,t,n={}){Rx.set(e,{permanent:!0,resolve:t,...n})}zx(`themes`,()=>ov(),{paletteOf:e=>dx(e)});const Bx=`placementThemes`;zx(Bx,sv,{paletteOf:(e,t)=>fx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of yte)zx(e,()=>t,{library:n,labelOf:r});function kte(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>mx(n.basePalette,e.styles[t])}],[`presets`,{members:Mx(e.presets)}]])}function Vx(e){return[...new Set([...Rx.keys(),...e.keys()])]}function Hx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=Rx.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(Ux(e,t))}const Ate=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function Ux(e,t){let n=Ate.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Vx(t).join(`, `)})`}const Wx=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function Gx(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*Kx(e){let t=[];qx(e,(e,n)=>(t.push([n,e]),e)),yield*t}function qx(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 jte(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const Jx=`groups.`,Yx=`menus.`,Xx=`menupages.`,Zx=`edit.`,Qx=`candybar.`,$x=[Jx,Yx,Xx,Zx,Qx];function eS(e){return $x.some(t=>e.startsWith(t))}const tS=`${Qx}menu`,nS=ta,rS={variable:tS,key:tS,member:nS},iS=`${Qx}diagnostics`,aS=`${Zi}://`,oS=`dispatch`,sS=`set-state`,cS=`step-state`,lS=`copy-text`,uS=`open-in-vscode`,dS=`toolbar-toggle`,fS=`set-config`,pS=`step-config`,mS=`save`,hS=`save-preset`,gS=`save-theme-default`,_S=`delete-preset`,vS=`reset-config`,yS=`apply-layout-op`,bS=`undo`,xS=`redo`,SS=`back`,CS=`rewind`,wS=`apply-update`,TS=`doctor-run`,ES=`doctor-fix`,DS=`doctor-mark`,OS=`probe`,kS=`slash`,AS=`repo-config`,jS=`copy-diagnostic`,MS=`range`,NS=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,PS=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function FS(e,t){if(e===iS)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!eS(e))return n;let r=PS(PS(e,Xx),Yx);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 IS(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const LS={[sS]:([,...e])=>e.flatMap((t,n)=>n%2==0?[FS(t,e[n+1])]:[]),[cS]:([,e,t])=>[NS(e,t)],[lS]:([,e])=>[`copy ${IS(e)}`],[uS]:([,e])=>[`open ${e} in vs code`],[dS]:()=>[`toggle the toolbar`],[fS]:([,e,t])=>[`save ${e} as ${t}`],[pS]:([,e,t])=>[`save ${NS(e,t)}`],[mS]:()=>[`save settings`],[hS]:()=>[`save as a new preset`],[gS]:()=>[`save this look for the theme`],[_S]:([,e])=>[`delete preset ${e}`],[vS]:([,...e])=>e.map(e=>`reset ${e}`),[yS]:([,e,t])=>[`edit ${t} in ${e}`],[bS]:()=>[`undo`],[xS]:()=>[`redo`],[SS]:()=>[`go back`],[CS]:()=>[`cancel edits`],[wS]:()=>[`update cc-candybar`],[TS]:()=>[`run doctor`],[ES]:([,e])=>[`fix ${e}`],[DS]:([,e,t])=>[`mark ${e} ${t}`],[kS]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[AS]:([,e,t])=>[`mark config in ${e} ${t}`],[jS]:()=>[`copy diagnostic`]},RS=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function zS(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=>LS[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function BS(e){return e.map(encodeURIComponent).join(`/`)}function VS(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function HS(e,t,n=zS(t)){let r=t.map(e=>`e=${encodeURIComponent(`${e.verb}/${BS(e.args)}`)}`);return WS(e,oS,[`does=${RS(n)}`,...r].join(`&`))}function US(e,t){return WS(e,OS,encodeURIComponent(t))}function WS(e,t,n){return`${aS}to/${e}/${t}/${n}`}function GS(e){return new r(e).getAll(`e`).map(YS)}const KS=new Set([sS,vS]);function qS(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&JS(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function JS(e,t){if(e.verb!==t.verb||!KS.has(e.verb))return;let[n,r]=[YS(e.value),YS(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function YS(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function XS(e){if(!e.startsWith(aS))return{ok:!1,problem:`expected a ${aS} link, got: ${e}`};let t=e.slice(aS.length);if(!t.startsWith(`to/`))return{ok:!1,problem:`the link is in ${t.includes(`/`)?`the direct verb form ${aS}<verb>/…`:`the bare copy form ${aS}<value>`}, which names no renderer: ${e}`};let n=t.slice(3),r=n.indexOf(`/`);if(r===-1)return{ok:!1,problem:`the link names a renderer and no click: ${e}`};try{return QS(n.slice(r+1),We(n.slice(0,r)))}catch(e){return{ok:!1,problem:e.message}}}function ZS(e){if(!$i(e))return!1;let t=e.slice(aS.length).split(`%`)[0];return!t.startsWith(`to/`)&&!`to/`.startsWith(t)}function QS(e,t){let n=e.indexOf(`/`);if(n===-1)return{ok:!1,problem:`the link carries no verb: ${e}`};let r=e.slice(0,n);try{return{ok:!0,to:t,verb:decodeURIComponent(r),value:e.slice(n+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${r}`}}}const $S=[`plugins`,`repo`];function eC({scope:e,name:t}){return`${e}.${t}`}function tC(e){return t=>t===e||t.startsWith(`${e}.`)}const nC=`self`;function rC(e){return $S.find(t=>e===t||e.startsWith(`${t}.`))}function iC(e,t){let n=rC(e);if(n===void 0||n===e)return``;let r=$S.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 aC=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*oC(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 sC=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,cC=RegExp(`^(?:(\\$)(?:\\.(${sC}))?|\\.(${sC})?)(?=[\\s)]|$)`);function lC(e,t,n){let r=cC.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 uC=/^(\w+)\b\s*([\s\S]*)$/;function*dC(e,t){let n=[t];for(let r of oC(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=uC.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:lC(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(lC(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const fC=/(?<![.$])\btemplate\s+$/;function*pC(e,t,n){let r=0;for(let i of[...e.matchAll(aC)]){let a=i.index+i[0].length;fC.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:lC(e.slice(a),t,n),index:i.index}),r=a}}function*mC(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...dC(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...pC(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 hC(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const gC=new WeakMap;function _C(e,t){let n=gC.get(t);return n===void 0&&(n=hC(e=>[...mC(e,t)]),gC.set(t,n)),n(e)}const vC=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${sC})`,`g`);function*yC({code:e,dot:t,root:n}){let r=e.replace(aC,``);for(let e of[...r.matchAll(vC)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function bC(e,t){let n=new Map;for(let r of _C(e,t))for(let e of yC(r))n.has(e)||n.set(e,r.via);return n}const xC=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,SC={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*CC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(aC)]){let a=e.slice(t,i.index),o=xC.exec(a);o===null?a.trim()!==``&&(n=0):(n=SC[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 wC(e,t){let n=new Map;for(let{code:r,via:i}of _C(e,t))for(let{name:e,site:t}of CC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function TC(e,t){let n=new Map;for(let{code:r,via:i}of _C(e,t))for(let e of r.matchAll(aC)){let t=e[0].slice(1,-1);if(!ZS(t))continue;let r=`${t}\0${i??`\0`}`;n.has(r)||n.set(r,{literal:t,via:i})}return[...n.values()]}const EC=e=>Object.keys(SC).filter(t=>SC[t]>=e).join(`|`),DC=RegExp(`(?<![\\w.$])(?:(?:${EC(1)})\\s+|(?:${EC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function OC(e,t){for(let{code:n}of _C(e,t))if(DC.test(n.replace(aC,`""`)))return!0;return!1}const kC=/(?<![\w.$])[A-Za-z_]\w*/g;function AC(e,t){let n=new Set;for(let{code:r}of _C(e,t))for(let[e]of r.replace(aC,``).matchAll(kC))n.add(e);return n}function jC(e,t){return new Set([...MC(e,t)].filter(e=>Object.hasOwn(t,e)))}function MC(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of _C(e,t))for(let{name:e}of pC(r,i,a))n.add(e);return n}const NC=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function PC(e,t,n){let r=NC(t),i=tC(t),a=[];for(let{dot:t,block:n}of dC(e,``)){let e=n.text.replace(aC,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[...pC(n.text,t,``),...CC(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*FC(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*IC(e){for(let[t,n]of FC(e))yield[t,n]}function LC(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 RC(e,t){return LC(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function zC(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),BC(r)&&n.add(e)};for(let[t,n]of IC(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`)&&ny(e.parse)===`json`}var VC=De((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Lt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return he(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function w(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:he(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function T(e,t){return{t:e,i:t,o:E,u:ee}}function E(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,te(e,0,0,n,!1,!1)),2)}function ee(e,t,n,r){let i=te(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function D(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 te(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 O(e,t){return{t:e,i:t,o:k,u:ne}}function k(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ne(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function A(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 re(e,t){return{t:e,i:t,o:ie,u:ae}}function ie(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ae(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function oe(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 se(e){return{t:Jt,i:e,o:ce,u:le}}function ce(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:he(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 le(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:he(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 ue(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function de(e){return e||Xt}function fe(e){return ue(e,oe)}function pe(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 me(e){return ue(e,A)}function he(e,t,n=!1,r){function i(){return ge(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ge(e,t,n,r,i){let a=_e(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{ve(a)}}function _e(e,t){let n=N.trackingDerivation,r=!t||!n;je();let i=N.allowStateChanges;r&&Te();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 ve(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Me(),e.R&&Ee(e.k),N.suppressReactionErrors=!1}function ye(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 be(e){return e instanceof xn}function xe(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Te(),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 Ee(t),!0}if(e.K===2)return Ee(t),!0}}return De(e),Ee(t),!1}}}function Se(e,t,n){De(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&&ke(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Oe(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ce(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)ke(t[n],e);e.K=-1}function we(e){let t=Te();try{return e()}finally{Ee(t)}}function Te(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Ee(e){N.trackingDerivation=e}function De(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Oe(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function ke(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ae(e))}function Ae(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function je(){N.inBatch++}function Me(){--N.inBatch===0&&(Ie(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ne(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ne))}function Pe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ae(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 Fe(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Re(e){return ue(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?he(t.name||`<unnamed action>`,t,e):r(n)?he(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ge(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=Te();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Ee(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){je();try{return e.apply(t)}finally{Me()}}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=he(`When-effect`,t);var a=He(t=>{ye(!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=Te();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{Ee(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=Te(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ee(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]=se({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=Te();je();try{return e()}finally{Me(),Ee(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 Pe(this)}reportChanged(){je(),Fe(this),Me()}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=se(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=re(`observable`),Qt=re(`observable.ref`,{A:y}),$t=re(`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=re(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=de(t);return new _n(e,pe(n),n.name,!0,n.equals)},array(e,t){let n=de(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,pe(n),n.name)},map(e,t){let n=de(t);return new rr(e,pe(n),n.name)},set(e,t){let n=de(t);return new or(e,pe(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=fe(Qt),rn=fe($t),an=fe(Zt),on=fe(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?oe(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=O(cn),un=me(O(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return A(ln,e,t);if(o(e))return me(O(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=he(`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(Pe(this),xe(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(Ne)}else xe(this)&&(this.Nt(),je(),this.rt=this.Rt(!1),Me());let e=this.rt;if(be(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||be(e)||be(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Se(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||(Ce(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),Ie())}X(){if(!this.isDisposed){je(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,xe(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Me()}}track(e){if(this.isDisposed)return;je(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Se(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ce(this),be(n)&&this.Pt(n.cause),Me()}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||(je(),Ce(this),Me()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return D(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=ue(Wn,D),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(()=>{we(()=>{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(()=>{we(()=>{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{je();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{Me()}return!0}S(e,t,n,r=!1){try{je();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{Me()}return!0}m(e,t,n=!1){try{je();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{Me()}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;je();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),Fe(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{Me()}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=ye,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=ve,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=_e,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=ye(!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)){je();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Me()}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),je(),r>=n.length&&(n.length=r+1),n[r]=i,Me()):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=we,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||{})}})),HC=De((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=D(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function E(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ee(e){return e===null?null:typeof e==`object`?``+e:e}function D(e,t){return o.hasOwnProperty.call(e,t)}let te=Object.getOwnPropertyDescriptors;function O(e,t){return!!(e&t)}function k(e,t,n){return n?e|=t:e&=~t,e}function ne(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let A=Symbol(`mobx administration`);var re=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 O(this.flags_,1)}set isBeingObserved(e){this.flags_=k(this.flags_,1,e)}get isPendingUnobservation(){return O(this.flags_,2)}set isPendingUnobservation(e){this.flags_=k(this.flags_,2,e)}get diffValue(){return+!!O(this.flags_,4)}set diffValue(e){this.flags_=k(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 ie=b(`Atom`,re);function ae(e,t=f,n=f){let r=new re(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function oe(e,t){return e===t}function se(e,t){return Li(e,t)}function ce(e,t){return Li(e,t,1)}let le=Object.is;function ue(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 de(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 fe(e){return e}function pe(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let me=`override`,he={annotationType_:me,make_:_e,extend_:ve};function ge(e){return e.annotationType_===me}function _e(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),D(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function ve(e,t,r,i){n(44,this.annotationType_)}function ye(e,t){return{annotationType_:e,options_:t,make_:be,extend_:xe}}function be(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,we(e,this,t,n,!1)),2)}function xe(e,t,n,r){let i=we(e,this,t,n);return e.defineProperty_(t,i,r)}function Se(e,t,r){ne(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 Ce(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 we(e,t,n,r,i=M.safeDescriptors){var a,o;Ce(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 Te(e,t){return{annotationType_:e,options_:t,make_:Ee,extend_:De}}function Ee(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&&(!D(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ae(e,this,t,n,!1,!1)),2)}function De(e,t,n,r){let i=Ae(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Oe(e,t,n){var r;ne(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 ke(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 Ae(e,t,n,r,i,a=M.safeDescriptors){ke(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 je(e,t){return{annotationType_:e,options_:t,make_:Me,extend_:Ne}}function Me(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ne(e,t,n,i){return Fe(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Pe(e,t,n){ne(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)[A],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[A],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 Fe(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??ue,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)}\``);ne(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Ei(e)[A];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??ue,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[A]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[A]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?ot:ut;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ot:ut).extend_(e,t,n,r))}function qe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:fe}),Qe=Ie(`observable.shallow`,{enhancer_:de}),$e=Ie(`observable.struct`,{enhancer_:pe});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?ue:e.deep===!1?fe:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??ue:ue}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 Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Pe)}let pt=je(dt),mt=ft(je(`computed.struct`,{equals:se})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Pe(pt,e,t);if(g(e))return ft(je(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 re{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=le){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 ee(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||le,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 O(this.flags_,1)}set isComputing(e){this.flags_=k(this.flags_,1,e)}get isRunningSetter(){return O(this.flags_,2)}set isRunningSetter(e){this.flags_=k(this.flags_,2,e)}get isBeingObserved(){return O(this.flags_,4)}set isBeingObserved(e){this.flags_=k(this.flags_,4,e)}get isPendingUnobservation(){return O(this.flags_,8)}set isPendingUnobservation(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(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 ee(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 O(this.flags_,1)}set isDisposed(e){this.flags_=k(this.flags_,1,e)}get isScheduled(){return O(this.flags_,2)}set isScheduled(e){this.flags_=k(this.flags_,2,e)}get isTrackPending(){return O(this.flags_,4)}set isTrackPending(e){this.flags_=k(this.flags_,4,e)}get isRunning(){return O(this.flags_,8)}set isRunning(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(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[A]=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=ye(N),kn=ye(`action.bound`,{bound:!0}),An=ye(En,{autoAction:!0}),jn=ye(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,Se)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Se(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(ye(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||le,_=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=te(t);return Fi(()=>{let t=Ei(e,i)[A];T(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,Oe)}let or=Te(`flow`),sr=Te(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Oe(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[A];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[A];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[A]||ie(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[A].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[A].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[A].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[A].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[A].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[A].defineProperty_(t,r);n(39)}function jr(e){if(ki(e))return e[A].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[A].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[A]}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[A]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Jr(e,t){let r=Ht();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Ei(e,n)[A];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),ki(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Ei(e,r)[A];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(A),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[A];return t===A?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):D(si,t)?si[t]:e[t]},set(e,t,n){let r=e[A];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 re(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Ft(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,A,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[A];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];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[A].spliceWithArray_(e,t,n)},push(...e){let t=this[A];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[A].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];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[A],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[A];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[A];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[A];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[A])}let mi={},hi=`delete`;var gi=class{constructor(e,t=ue,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[A]=mi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=ae(`${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),fe,`${this.name_}.${E(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_}.${E(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)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=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`,Vi(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=ue,n=`ObservableSet@`+u()){this.name_=void 0,this[A]=yi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=ae(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`,Vi(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 re(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!D(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return D(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_,fe,`${this.name_}.${E(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_),!D(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(),T(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.`),D(e,A))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,A,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[A].getObservablePropValue_(e)},set(t){return this[A].setObservablePropValue_(e,t)}})}function ki(e){return h(e)?Di(e[A]):!1}function Ai(e,t,n){e.appliedAnnotations_[n]=t}function ji(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ge(t)&&D(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[A].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[A],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ie(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[A]))return e[A];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(Mi(e,t));if(ie(e)||At(e)||vn(e)||P(e)||xi(e))return e;if(e[A])return e[A];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 Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(D(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||xi(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:A}),e.$mobx=A,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=le,e.compareIdentity=oe,e.compareShallow=ce,e.compareStructural=se,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=ae,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=he,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),X=De(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=VC():t.exports=HC()}))();function UC(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(UC);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(UC)}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 GC(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 KC(e){return typeof e==`string`?e:String(e)}function qC(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 JC(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 YC=class extends Error{constructor(e,t){super(t),this.variable=e}};function XC(e){return e instanceof YC?e:e instanceof Error&&e.cause!==void 0?XC(e.cause):void 0}const ZC=e=>co(e);var QC=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,ZC(n)||cw(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=ZC(n)?null:r.now()}read(){let e=this.cell.get();if(ZC(e))throw new YC(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){ZC(e)||cw(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},$C=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},ew=class{constructor(e){this.deriver=e}read(){return this.deriver()}},tw=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new $C(`Variable "${e}"`,()=>{let e=n();return cw(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},nw=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new ew(()=>{let e=n();return cw(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},rw=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(sw(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=sw(e);ow(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},iw=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new $C(`Variable "${e}"`,()=>sw(t()),ow)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function aw(e){return JSON.stringify(e)}function ow(e,t){return aw(e)===aw(t)}function sw(e){return e.kind===`ok`?{kind:`ok`,value:WC(e.value)}:e}function cw(e,t,n,r){let i=GC(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var lw=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new QC(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new rw(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new iw(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`?tw:nw;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new ew(n);let r=new $C(`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 rw))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?e:F(aw(e))}try{return F(String(t.read()))}catch(e){return XC(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):so(`unread`)}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof tw||t instanceof iw)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}},uw=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?yw(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}},dw=class extends uw{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},fw=class extends uw{name=`EvalError`;kind=`EvalError`},pw=class extends fw{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=bw(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}},mw=class extends fw{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}},hw=class extends fw{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}},gw=class extends hw{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)}`}},_w=class extends fw{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},vw=class extends fw{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function yw(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 bw(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:xw(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 xw(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 Sw(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Cw=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`]]),ww={left:`{{`,right:`}}`};var Tw=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=ww){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 dw(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&&Ew(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);Ew(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);Ew(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(;Ew(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`;Ew(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&&(Ow(e)||Dw(e)&&Ow(this.src[this.offset+1]??``)||e===`.`&&Ow(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Nw(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(Dw(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);kw(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);Aw(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);jw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Ow(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Ow(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),Dw(this.src[this.offset]??``)&&this.advanceBy(1);Ow(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return kw(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);Pw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Nw(this.src[this.offset+1]??``);)for(this.advanceBy(1);Pw(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),!Nw(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;Pw(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Nw(this.src[this.offset+1]??``);)for(this.advanceBy(1);Pw(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(;Pw(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Cw.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 mw(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function tT(e,t,n){let r=eT(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new mw(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function nT(e,t){if(t(e)!==!1)for(let n of rT(e))nT(n,t)}function rT(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 Tw(e)}}const iT=Symbol(`go-template-js.MISSING`);function aT(e,t){if(e==null)return iT;if(e instanceof Map)return e.has(t)?e.get(t):iT;if(Array.isArray(e))return iT;if(typeof e==`object`){let n=e;return t in n?n[t]:iT}return iT}function oT(e,t){let n=e;for(let e of t){if(n===iT)return iT;n=aT(n,e)}return n}function sT(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)=>sT(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)||!sT(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=>sT(e[n],t[n])):!1}return!1}const cT=new WeakSet;function lT(e){return cT.add(e),e}function uT(e){return cT.has(e)}function dT(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 fT(e,t){return{eq:{fn:(e,...t)=>t.some(t=>hT(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!hT(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>gT(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>gT(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>gT(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>gT(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>_T(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=vT(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>bT(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>CT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${CT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>MT(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)=>ET(CT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>kT(CT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>jT(CT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!dT(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function pT(){return{and:lT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!dT(t))return t;return t}}),or:lT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),dT(t))return t;return t}})}}function mT(e,t){return{...fT(e,t),...pT()}}function hT(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):sT(e,t)}function gT(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 _T(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function vT(e,t){if(Array.isArray(e)||typeof e==`string`){let n=yT(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 ${xT(t)}`);return e[t]}throw Error(`index: cannot index ${xT(e)}`)}function yT(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 ${ST(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function bT(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]=yT(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 xT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function ST(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 CT(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+=wT(a,t),r=o}return n}function wT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const TT={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function ET(e){return e.replace(/[\0"'&<>]/g,e=>TT[e]??e)}const DT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},OT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function kT(e){let t=``;for(let n of e){let e=DT[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 AT=new TextEncoder;function jT(e){let t=``,n=AT.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 MT(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+=NT(l??``,u,d,n,r),o=c+1}return i}function NT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?PT(t,n):PT(t,wT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${ST(n)}=${wT(n,r)})`:PT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return PT(t,FT(n,r,i));case`q`:return PT(t,JSON.stringify(wT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${ST(n)}=${wT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return PT(t,Number(n).toFixed(i))}case`t`:return PT(t,dT(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 PT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${ST(n)}=${wT(n,r)})`:typeof n==`bigint`?PT(t,n.toString(16)):PT(t,Math.trunc(n).toString(16));default:return`%!${e}(${ST(n)}=${wT(n,r)})`}}function PT(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?IT([...e.entries()],t,n):LT(e)?IT(Object.entries(e),t,n):String(e)}function IT(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 LT(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 RT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function zT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function BT(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 HT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],UT=new Set([`default`,`zero`,`error`]);function WT(e){if(e===void 0)return`default`;if(UT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${GT(e)}`)}function GT(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 KT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${GT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${GT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${GT(e.right)}`);return{left:e.left,right:e.right}}}function qT(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function JT(e){let t=new Set(HT);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${HT.join(`, `)}`)}),qT(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 YT=Object.freeze({kind:`break`}),XT=Object.freeze({kind:`continue`}),ZT={kind:`none`};let QT;(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{QT=(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 $T(e){let t=new Set,n=e=>{nT(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 eE={kind:`dynamic`};function tE(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=SE(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:eE}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return eE;let t=e.cmds[0];if(t===void 0)return eE;let n=t.args[0];return n===void 0||n.type!==`Identifier`?eE:{kind:`call`,name:n.ident,args:t.args.slice(1).map(tE)}}default:return eE}}function nE(e){let t=[],n=e=>{nT(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(tE);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 rE=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??dE,this.isT=e.isT??iE,this.missingKey=WT(e.missingKey),this.delims=KT(e.delims),this.funcs=JT({...mT(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=Hw(e,this.delims,t);return QT(n.source,e=>this.evalParsed(n,e),n.defines,$T(n),nE(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=RT(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 YT;case`Continue`:throw XT;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 hw(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Tw(e)}}evalIf(e,t,n){dT(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(dT(r)){let i=zT(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=yE(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=zT(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===XT)continue;throw e}}}catch(e){if(e===YT)return;throw e}}evalTemplateInvoke(e,t,n){let r=Bw(n.defines,e.name);if(!r)throw new hw(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=zT(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=zT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=Bw(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 hw(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,ZT);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 hw(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new hw(`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 gw(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=uT(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){oE(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof vw?new vw(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof xw?new xw(t.message,r,{source:i.source}):t instanceof pw?t:new hw(`error calling ${e}: ${_E(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 SE(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 gw(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 hw(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=oT(e,t);if(i!==iT)return i;if(this.missingKey===`error`)throw new bw(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=BT(t,i);if(!a.found)throw new hw(`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 iE=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function aE(e){return new rE(e)}function oE(e,t,n,r,i,a=dE,o=uE,s=iE){let{argTypes:c,arity:l}=t,u=sE(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new _w(e,u,n.length,r,{source:i});let d=cE(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!lE(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new yw(e,t+1,l,r,{source:i}):new vw(e,t+1,gE(c),vE(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(!pE(n[f],l))throw new vw(e,t+1,`${gE(`ordered`)} of the same kind as ${vE(n[f])}`,vE(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!mE(n[p],l))throw new vw(e,t+1,`${gE(`comparable`)} of the same kind as ${vE(n[p])}`,vE(l),r,{source:i})}}}function sE(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 cE(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 lE(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 LT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||LT(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||LT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||LT(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 fE(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function uE(e){return e}function dE(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 vw(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,vE(e),{line:0,column:0,offset:0})}function fE(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function pE(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function mE(e,t){let n=hE(e),r=hE(t);return n===`nil`||r===`nil`?!0:n===r}function hE(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 gE(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 _E(e){return e instanceof Error?e.message:String(e)}function vE(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function yE(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?bE([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?bE(Object.entries(e)):[]}function bE(e){return[...e].sort((e,t)=>xE(e[0],t[0]))}function xE(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 SE(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 CE(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function wE(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 TE(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 EE(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=TE(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 DE(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=TE(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 kE(e){return JSON.stringify(e)??`null`}function AE(){return{atoi:{fn:e=>CE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>EE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>DE(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>wE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>OE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>kE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const jE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function ME(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*jE[a],n=n.slice(e[0].length)}return t?-r:r}function NE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<jE.us?`${Math.floor(n)}ns`:n<jE.ms?PE(n,jE.us,3,`µs`):n<jE.s?PE(n,jE.ms,6,`ms`):FE(n),t?`-${r}`:r}function PE(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/jE.h);e-=t*jE.h;let n=Math.floor(e/jE.m);e-=n*jE.m;let r=Math.floor(e/jE.s),i=e-r*jE.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 IE(e){return e*jE.s}function LE(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 RE(e,t){let n=t().getTime()-LE(e).getTime();return NE(Math.round(n/1e3)*1e9)}const zE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],BE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],VE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],HE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function UE(e){return e<10?`0${e}`:String(e)}function WE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function GE(e){return e<10?` ${e}`:String(e)}function KE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${UE(Math.floor(n/60))}${UE(n%60)}`}function qE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${UE(Math.floor(n/60))}:${UE(n%60)}`}function JE(e){return`${e>=0?`+`:`-`}${UE(Math.floor(Math.abs(e)/60))}`}function YE(e){return e===0?`Z`:KE(e)}function XE(e){return e===0?`Z`:qE(e)}function ZE(e){return e===0?`Z`:JE(e)}function QE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const $E=[[`.000000000`,e=>`.${QE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=QE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${QE(e.ms,6,!1)}`],[`.999999`,e=>{let t=QE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${WE(e.ms)}`],[`.999`,e=>{let t=WE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>zE[e.month-1]??`January`],[`Monday`,e=>VE[e.weekday]??`Monday`],[`Z07:00`,e=>XE(e.offsetMinutes)],[`-07:00`,e=>qE(e.offsetMinutes)],[`Z0700`,e=>YE(e.offsetMinutes)],[`-0700`,e=>KE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>BE[e.month-1]??`Jan`],[`Mon`,e=>HE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>JE(e.offsetMinutes)],[`Z07`,e=>ZE(e.offsetMinutes)],[`15`,e=>UE(e.hour)],[`01`,e=>UE(e.month)],[`02`,e=>UE(e.day)],[`_2`,e=>GE(e.day)],[`03`,e=>UE(e.hour12)],[`04`,e=>UE(e.minute)],[`05`,e=>UE(e.second)],[`06`,e=>UE(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 eD(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of $E)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const tD={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function nD(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const rD=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function iD(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=nD(new Intl.DateTimeFormat(`en-US`,{...tD,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=nD(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=aD(nD(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=rD.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 aD(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 oD(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function sD(e,t){return eD(e,iD(LE(t),oD()))}function cD(e,t,n){return eD(e,iD(LE(t),n))}function lD(e,t){let n=LE(t),r=ME(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function uD(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:NE(IE(t))}return typeof e==`bigint`?NE(IE(Number(e))):typeof e==`number`?NE(IE(e)):`0s`}const dD=36e11*24*365,fD=36e11*24*30,pD=36e11*24,mD=36e11,hD=6e10,gD=1e9;function _D(e){let t=ME(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>dD?`${Math.floor(n/dD)}y`:n>fD?`${Math.floor(n/fD)}mo`:n>pD?`${Math.floor(n/pD)}d`:n>mD?`${Math.floor(n/mD)}h`:n>hD?`${Math.floor(n/hD)}m`:n>gD?`${Math.floor(n/gD)}s`:`0s`}function vD(e){let t=iD(LE(e),oD());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function yD(e,t){let n=iD(LE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function bD(e){return e()}const xD=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],SD=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function CD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function wD(e,t,n){return[e.slice(t,t+n),t+n]}function TD(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 ED(e,t){for(let[n,r]of xD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function DD(e,t){for(let[n,r]of SD.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 kD(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 AD(e,t){if(e[t]===` `){let[n,r]=TD(e,t+1,1,1);return[n,r]}return TD(e,t,1,2)}function jD(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]=TD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=TD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=TD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function MD(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]=TD(e,t+1,2,2);return[n*r*60,i]}return jD(e,t,n)}function ND(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 PD(e,t,n){let[r,i]=wD(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]=ED(t,n);return i.month=e,[r,i]}case`Monday`:return[OD(t,n),i];case`Jan`:{let[e,r]=DD(t,n);return i.month=e,[r,i]}case`Mon`:return[kD(t,n),i];case`2006`:{let[e,r]=TD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=TD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=TD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=TD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=AD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=TD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=TD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=TD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=TD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=TD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=TD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=TD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=TD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=TD(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[ND(t,n),i];case`-0700`:{let[e,r]=jD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=jD(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]=TD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=MD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=MD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=MD(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]=PD(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]=PD(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]=PD(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 ID=`.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 LD(e,t){let n=0,r=0,i=CD();for(;n<e.length;){let a=!1;for(let o of ID)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 RD(e,t){return LD(e,t)}function zD(e){return String(Math.floor(LE(e).getTime()/1e3))}function BD(e=()=>new Date){return{now:{fn:()=>bD(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>sD(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>cD(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>lD(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>vD(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>yD(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>uD(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>_D(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>RD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>RE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>zD(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 HD(...e){for(let t of e)if(!VD(t))return t}function UD(e,t){return VD(t)?e:t}function WD(e){return JSON.parse(e)}function GD(e,t,n){return dT(n)?e:t}function KD(e){return JSON.stringify(e)??`null`}function qD(e){return JSON.stringify(e,null,2)??`null`}function JD(){return{default:{fn:(e,t)=>UD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>VD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>HD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>GD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>WD(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>KD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>qD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function YD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function XD(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 YD(...t)}function ZD(e,t){return e[t]}function QD(e,t){return t in e}function $D(e){return Object.keys(e)}function eO(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 tO(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function nO(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 rO(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function iO(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function aO(e,t,n){return e[t]=n,e}function oO(e,t){return delete e[t],e}function sO(e){return Object.values(e)}function cO(){return{dict:{fn:(...e)=>YD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>ZD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>aO(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>oO(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>$D(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>sO(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>iO(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>rO(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>nO(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>QD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>eO(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>tO(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function lO(e){throw new xw(e)}function uO(){return{fail:{fn:e=>lO(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 dO(...e){for(let t of e)if(VD(t))return!1;return!0}function fO(...e){for(let t of e)if(!VD(t))return!0;return!1}function pO(e,t){return[...e,t]}function mO(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 hO(e){return e.filter(e=>!VD(e))}function gO(...e){let t=[];for(let n of e)t.push(...n);return t}const _O={line:0,column:0,offset:0};function vO(e,t,n,r){return new vw(e,t,n,r,_O)}function yO(...e){if(e.length<3)throw vO(`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(!xO(t))throw vO(`dig`,e.length-1,`dict`,SO(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw vO(`dig`,e,`string`,SO(r[e]));return bO(t,n,r,e.length)}function bO(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(!xO(a))throw vO(`dig`,r-1,`dict at intermediate key`,SO(a));return bO(a,t,n.slice(1),r)}function xO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function SO(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function CO(e){return e[0]}function wO(e,t){return t.some(t=>sT(t,e))}function TO(e){return e.slice(0,-1)}function EO(e){return e[e.length-1]}function DO(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 kO(e,t){return[t,...e]}function AO(e){return e.slice(1)}function jO(e){return[...e].reverse()}function MO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function NO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function PO(e){let t=[];for(let n of e)t.some(e=>sT(e,n))||t.push(n);return t}function FO(e,...t){return e.filter(e=>!t.some(t=>sT(t,e)))}function IO(){return{list:{fn:(...e)=>OO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>CO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>EO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>AO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>TO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>DO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>jO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>PO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>FO(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>wO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>hO(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>MO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>gO(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>mO(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>kO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>pO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>NO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>pO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>OO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>yO(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>dO(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>fO(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function LO(...e){return e.reduce((e,t)=>e+t,0)}function RO(e){return e+1}function zO(e){return e+1}function BO(...e){return e.reduce((e,t)=>e+t,0)}function VO(e){return Math.ceil(e)}function HO(e,t){return Math.trunc(e/t)}function UO(e,...t){return t.reduce((e,t)=>e/t,e)}function WO(e){return Math.floor(e)}function GO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function KO(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function qO(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function JO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function YO(e,t){return e%t}function XO(...e){return e.reduce((e,t)=>e*t,1)}function ZO(...e){return e.reduce((e,t)=>e*t,1)}function QO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function $O(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 ek(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),$O(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return $O(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:$O(n,i+t,r).join(` `)}default:return``}}function tk(e,t){return e-t}function nk(e,...t){return t.reduce((e,t)=>e-t,e)}function rk(e){return $O(0,e,e<0?-1:1)}function ik(){return{add:{fn:(...e)=>LO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>tk(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>XO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>HO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>YO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>qO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>GO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>WO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>VO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>QO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>BO(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>nk(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>ZO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>UO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>RO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>zO(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>KO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>JO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>GO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>ek(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>rk(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>$O(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function ak(e){return Array.from(e)}function ok(e,t){return e===``?ak(t):t.split(e)}function sk(e,t){let n=ak(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function ck(e,t,n){let r=ak(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const lk={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},uk=/^[-_\s]$/,dk=/^\p{P}$/u,fk=/^\p{L}$/u,pk=/^\p{Lu}$/u,mk=/^\p{N}$/u;function hk(e){return e!==void 0&&uk.test(e)}function gk(e){return e!==void 0&&fk.test(e)}function _k(e){return e!==void 0&&pk.test(e)}function vk(e){return e!==void 0&&mk.test(e)}function yk(e){return e!==void 0&&dk.test(e)}function bk(e,t){if(t>=e.length)return{word:{wt:lk.Invalid,text:``},next:t};let n=e[t],r=t+1;if(hk(n)){for(;r<e.length&&hk(e[r]);)r++;return{word:{wt:lk.Connector,text:e.slice(t,r).join(``)},next:r}}if(yk(n)){for(;r<e.length&&yk(e[r]);)r++;return{word:{wt:lk.Punct,text:e.slice(t,r).join(``)},next:r}}if(_k(n)){if(r>=e.length)return{word:{wt:lk.UpperCase,text:n},next:r};if(_k(e[r])){let n=r;for(;n<e.length&&_k(e[n]);)n++;return n<e.length&&gk(e[n])?{word:{wt:lk.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:lk.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(gk(e[r])){let n=r+1;for(;n<e.length&&gk(e[n])&&!_k(e[n]);)n++;return{word:{wt:lk.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:lk.UpperCase,text:n},next:r}}if(gk(n)){for(;r<e.length&&gk(e[r])&&!_k(e[r]);)r++;return{word:{wt:lk.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(vk(n)){for(;r<e.length&&vk(e[r]);)r++;return{word:{wt:lk.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!hk(e[r])&&!gk(e[r])&&!vk(e[r])&&!yk(e[r]);)r++;return{word:{wt:lk.Other,text:e.slice(t,r).join(``)},next:r}}function xk(e,t,n){if(t.wt!==lk.UpperCase&&t.wt!==lk.Connector){e.push(t.text);return}for(let r of t.text)hk(r)?e.push(n):_k(r)?e.push(r.toLowerCase()):e.push(r)}function Sk(e,t){if(e.length===0)return``;let n=ak(e),r=[],{word:i,next:a}=bk(n,0);for(;a<n.length;){i.wt!==lk.Connector&&xk(r,i,t);let e=i,o=i;if({word:i,next:a}=bk(n,a),e.wt===lk.Number){for(;i.wt===lk.Alphabet||i.wt===lk.Number;)xk(r,i,t),{word:i,next:a}=bk(n,a);i.wt!==lk.Invalid&&i.wt!==lk.Punct&&i.wt!==lk.Connector&&r.push(t);continue}if(e.wt===lk.Connector){xk(r,o,t);continue}if(e.wt===lk.Punct)continue;if(i.wt!==lk.Number){i.wt!==lk.Connector&&i.wt!==lk.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=bk(n,a),i.wt!==lk.Alphabet){xk(r,s,t),i.wt!==lk.Connector&&i.wt!==lk.Punct&&r.push(t);continue}for(r.push(t),xk(r,s,t);i.wt===lk.Alphabet||i.wt===lk.Number;)xk(r,i,t),{word:i,next:a}=bk(n,a);i.wt!==lk.Invalid&&i.wt!==lk.Connector&&i.wt!==lk.Punct&&r.push(t)}return xk(r,i,t),r.join(``).toLowerCase()}function Ck(e){if(e.length===0)return``;let t=ak(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!hk(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++,hk(i)&&hk(e)){n.push(e);continue}hk(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function wk(e){return Ck(e)}function Tk(...e){return e.join(` `)}function Ek(e,t){return t.includes(e)}function Dk(e,t){return t.startsWith(e)}function Ok(e,t){return t.endsWith(e)}function kk(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 Ew(e){return e===` `||e===` `||e===`\r`||e===`
|
|
65
|
+
`}function Dw(e){return e===`+`||e===`-`}function Ow(e){return e>=`0`&&e<=`9`}function kw(e){return Ow(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Aw(e){return e>=`0`&&e<=`7`}function jw(e){return e===`0`||e===`1`}function Mw(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Nw(e){return Mw(e)||e===`_`}function Pw(e){return Nw(e)||Ow(e)}let Fw,Iw;function Lw(e,t){return Iw(e,t)}var Rw=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{Fw=(t,n)=>new e(t,n),Iw=(e,t)=>e.#e.get(t)??(e.#t&&Iw(e.#t,t))}has(e){return Iw(this,e)!==void 0}};function zw(e,t,n=Rw.EMPTY){return new Bw(e,t,n).parseTemplate()}var Bw=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new Tw(e,t):new Tw(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:Uw(n)});return n}errAt(e,t,n={}){return new dw(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 ${Uw(e)}`,{found:Uw(e)})}return{root:e,defines:Fw(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=Hw(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 Vw(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${Uw(n)} at top level`,{found:Uw(n)})}return Vw(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 dw(`{{${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 dw(`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:Uw(e)});return Zw(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(!Ww(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:Uw(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=[Gw(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(Gw(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;Ww(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 Gw(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Zw(e.value,e.pos,this.source)};case`Number`:return qw(e);case`Char`:return Jw(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 ${Uw(e)}`,{expected:`command argument`,found:Uw(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 Vw(e,t){return{type:`List`,pos:e,nodes:t}}function Hw(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function Uw(e){return e.type===`EOF`?`end of input`:e.value||e.type}function Ww(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 Gw(e){return{type:`Variable`,pos:e.pos,idents:Kw(e.value)}}function Kw(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function qw(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=Yw(i);return{...s,intValue:e}}if(a){let e=Xw(i);return{...s,floatValue:e}}let c=Xw(i);return{...s,complexValue:[0,c]}}function Jw(e,t){let n=Qw(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 Yw(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 Xw(e){return Number(e)}function Zw(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 dw(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Qw(e,t,n){let r=Zw(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new dw(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function $w(e,t){if(t(e)!==!1)for(let n of eT(e))$w(n,t)}function eT(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 Sw(e)}}const tT=Symbol(`go-template-js.MISSING`);function nT(e,t){if(e==null)return tT;if(e instanceof Map)return e.has(t)?e.get(t):tT;if(Array.isArray(e))return tT;if(typeof e==`object`){let n=e;return t in n?n[t]:tT}return tT}function rT(e,t){let n=e;for(let e of t){if(n===tT)return tT;n=nT(n,e)}return n}function iT(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)=>iT(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)||!iT(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=>iT(e[n],t[n])):!1}return!1}const aT=new WeakSet;function oT(e){return aT.add(e),e}function sT(e){return aT.has(e)}function cT(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 lT(e,t){return{eq:{fn:(e,...t)=>t.some(t=>fT(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!fT(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>pT(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>pT(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>pT(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>pT(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>mT(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=hT(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>_T(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>bT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${bT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>kT(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>MT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>MT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>CT(bT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>ET(bT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>OT(bT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!cT(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function uT(){return{and:oT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!cT(t))return t;return t}}),or:oT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),cT(t))return t;return t}})}}function dT(e,t){return{...lT(e,t),...uT()}}function fT(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):iT(e,t)}function pT(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 mT(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function hT(e,t){if(Array.isArray(e)||typeof e==`string`){let n=gT(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 ${vT(t)}`);return e[t]}throw Error(`index: cannot index ${vT(e)}`)}function gT(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 ${yT(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function _T(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]=gT(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 vT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function yT(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 bT(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+=xT(a,t),r=o}return n}function xT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const ST={"\0":`�`,'"':`"`,"'":`'`,"&":`&`,"<":`<`,">":`>`};function CT(e){return e.replace(/[\0"'&<>]/g,e=>ST[e]??e)}const wT={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},TT=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function ET(e){let t=``;for(let n of e){let e=wT[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!TT.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const DT=new TextEncoder;function OT(e){let t=``,n=DT.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 kT(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+=AT(l??``,u,d,n,r),o=c+1}return i}function AT(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?jT(t,n):jT(t,xT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${yT(n)}=${xT(n,r)})`:jT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return jT(t,MT(n,r,i));case`q`:return jT(t,JSON.stringify(xT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${yT(n)}=${xT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return jT(t,Number(n).toFixed(i))}case`t`:return jT(t,cT(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 jT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${yT(n)}=${xT(n,r)})`:typeof n==`bigint`?jT(t,n.toString(16)):jT(t,Math.trunc(n).toString(16));default:return`%!${e}(${yT(n)}=${xT(n,r)})`}}function jT(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 MT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>MT(e,t,n)).join(` `)}]`:e instanceof Map?NT([...e.entries()],t,n):PT(e)?NT(Object.entries(e),t,n):String(e)}function NT(e,t,n){let r=e=>MT(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 PT(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 FT(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function IT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function LT(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 RT(e,t,n){e.vars.set(t,n)}const zT=[`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 VT(e){if(e===void 0)return`default`;if(BT.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${HT(e)}`)}function HT(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 UT(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${HT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${HT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${HT(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 GT(e){let t=new Set(zT);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 ${zT.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 KT=Object.freeze({kind:`break`}),qT=Object.freeze({kind:`continue`}),JT={kind:`none`};let YT;(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{YT=(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 XT(e){let t=new Set,n=e=>{$w(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 ZT={kind:`dynamic`};function QT(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=yE(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:ZT}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return ZT;let t=e.cmds[0];if(t===void 0)return ZT;let n=t.args[0];return n===void 0||n.type!==`Identifier`?ZT:{kind:`call`,name:n.ident,args:t.args.slice(1).map(QT)}}default:return ZT}}function $T(e){let t=[],n=e=>{$w(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(QT);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var eE=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??cE,this.isT=e.isT??tE,this.missingKey=VT(e.missingKey),this.delims=UT(e.delims),this.funcs=GT({...dT(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=zw(e,this.delims,t);return YT(n.source,e=>this.evalParsed(n,e),n.defines,XT(n),$T(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=FT(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 KT;case`Continue`:throw qT;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 fw(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Sw(e)}}evalIf(e,t,n){cT(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(cT(r)){let i=IT(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=gE(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=IT(t,o);if(i.length===1)RT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;RT(a,e,r),RT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===qT)continue;throw e}}}catch(e){if(e===KT)return;throw e}}evalTemplateInvoke(e,t,n){let r=Lw(n.defines,e.name);if(!r)throw new fw(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=IT(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=IT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=Lw(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 fw(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,JT);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)RT(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 fw(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new fw(`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 pw(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=sT(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){rE(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof hw?new hw(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof vw?new vw(t.message,r,{source:i.source}):t instanceof uw?t:new fw(`error calling ${e}: ${mE(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 yE(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 pw(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 fw(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=rT(e,t);if(i!==tT)return i;if(this.missingKey===`error`)throw new _w(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=LT(t,i);if(!a.found)throw new fw(`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(MT(e,this.toString,this.isT)))}};const tE=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function nE(e){return new eE(e)}function rE(e,t,n,r,i,a=cE,o=sE,s=tE){let{argTypes:c,arity:l}=t,u=iE(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new mw(e,u,n.length,r,{source:i});let d=aE(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!oE(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new gw(e,t+1,l,r,{source:i}):new hw(e,t+1,pE(c),hE(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(!uE(n[f],l))throw new hw(e,t+1,`${pE(`ordered`)} of the same kind as ${hE(n[f])}`,hE(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!dE(n[p],l))throw new hw(e,t+1,`${pE(`comparable`)} of the same kind as ${hE(n[p])}`,hE(l),r,{source:i})}}}function iE(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 aE(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 oE(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 PT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||PT(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||PT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||PT(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 lE(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function sE(e){return e}function cE(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 hw(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,hE(e),{line:0,column:0,offset:0})}function lE(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function uE(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function dE(e,t){let n=fE(e),r=fE(t);return n===`nil`||r===`nil`?!0:n===r}function fE(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 pE(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 mE(e){return e instanceof Error?e.message:String(e)}function hE(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function gE(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?_E([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?_E(Object.entries(e)):[]}function _E(e){return[...e].sort((e,t)=>vE(e[0],t[0]))}function vE(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 yE(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 bE(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function xE(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 SE(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 CE(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=SE(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 wE(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=SE(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 TE(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 EE(e){return JSON.stringify(e)??`null`}function DE(){return{atoi:{fn:e=>bE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>CE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>wE(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>xE(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>TE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>EE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const OE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function kE(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*OE[a],n=n.slice(e[0].length)}return t?-r:r}function AE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<OE.us?`${Math.floor(n)}ns`:n<OE.ms?jE(n,OE.us,3,`µs`):n<OE.s?jE(n,OE.ms,6,`ms`):ME(n),t?`-${r}`:r}function jE(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 ME(e){let t=Math.floor(e/OE.h);e-=t*OE.h;let n=Math.floor(e/OE.m);e-=n*OE.m;let r=Math.floor(e/OE.s),i=e-r*OE.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 NE(e){return e*OE.s}function PE(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 FE(e,t){let n=t().getTime()-PE(e).getTime();return AE(Math.round(n/1e3)*1e9)}const IE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],LE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],RE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],zE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function BE(e){return e<10?`0${e}`:String(e)}function VE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function HE(e){return e<10?` ${e}`:String(e)}function UE(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 GE(e){return`${e>=0?`+`:`-`}${BE(Math.floor(Math.abs(e)/60))}`}function KE(e){return e===0?`Z`:UE(e)}function qE(e){return e===0?`Z`:WE(e)}function JE(e){return e===0?`Z`:GE(e)}function YE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const XE=[[`.000000000`,e=>`.${YE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=YE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${YE(e.ms,6,!1)}`],[`.999999`,e=>{let t=YE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${VE(e.ms)}`],[`.999`,e=>{let t=VE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>IE[e.month-1]??`January`],[`Monday`,e=>RE[e.weekday]??`Monday`],[`Z07:00`,e=>qE(e.offsetMinutes)],[`-07:00`,e=>WE(e.offsetMinutes)],[`Z0700`,e=>KE(e.offsetMinutes)],[`-0700`,e=>UE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>LE[e.month-1]??`Jan`],[`Mon`,e=>zE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>GE(e.offsetMinutes)],[`Z07`,e=>JE(e.offsetMinutes)],[`15`,e=>BE(e.hour)],[`01`,e=>BE(e.month)],[`02`,e=>BE(e.day)],[`_2`,e=>HE(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 ZE(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of XE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const QE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function $E(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const eD=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function tD(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=$E(new Intl.DateTimeFormat(`en-US`,{...QE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=$E(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=nD($E(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=eD.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 nD(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 rD(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function iD(e,t){return ZE(e,tD(PE(t),rD()))}function aD(e,t,n){return ZE(e,tD(PE(t),n))}function oD(e,t){let n=PE(t),r=kE(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function sD(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:AE(NE(t))}return typeof e==`bigint`?AE(NE(Number(e))):typeof e==`number`?AE(NE(e)):`0s`}const cD=36e11*24*365,lD=36e11*24*30,uD=36e11*24,dD=36e11,fD=6e10,pD=1e9;function mD(e){let t=kE(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>cD?`${Math.floor(n/cD)}y`:n>lD?`${Math.floor(n/lD)}mo`:n>uD?`${Math.floor(n/uD)}d`:n>dD?`${Math.floor(n/dD)}h`:n>fD?`${Math.floor(n/fD)}m`:n>pD?`${Math.floor(n/pD)}s`:`0s`}function hD(e){let t=tD(PE(e),rD());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function gD(e,t){let n=tD(PE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function _D(e){return e()}const vD=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],yD=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function bD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function xD(e,t,n){return[e.slice(t,t+n),t+n]}function SD(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 CD(e,t){for(let[n,r]of vD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function wD(e,t){for(let[n,r]of yD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function TD(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 ED(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 DD(e,t){if(e[t]===` `){let[n,r]=SD(e,t+1,1,1);return[n,r]}return SD(e,t,1,2)}function OD(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]=SD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=SD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=SD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function kD(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]=SD(e,t+1,2,2);return[n*r*60,i]}return OD(e,t,n)}function AD(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 jD(e,t,n){let[r,i]=xD(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function MD(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=CD(t,n);return i.month=e,[r,i]}case`Monday`:return[TD(t,n),i];case`Jan`:{let[e,r]=wD(t,n);return i.month=e,[r,i]}case`Mon`:return[ED(t,n),i];case`2006`:{let[e,r]=SD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=SD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=SD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=SD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=DD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=SD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=SD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=SD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=SD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=SD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=SD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=SD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=SD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=SD(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[AD(t,n),i];case`-0700`:{let[e,r]=OD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=OD(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]=SD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=kD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=kD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=kD(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]=jD(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]=jD(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]=jD(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 ND=`.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 PD(e,t){let n=0,r=0,i=bD();for(;n<e.length;){let a=!1;for(let o of ND)if(e.startsWith(o,n)){let[e,s]=MD(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 FD(e,t){return PD(e,t)}function ID(e){return String(Math.floor(PE(e).getTime()/1e3))}function LD(e=()=>new Date){return{now:{fn:()=>_D(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>iD(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>aD(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>oD(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>hD(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>gD(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>sD(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>mD(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>FD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>FE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>ID(e),argTypes:[`value`],arity:{kind:`exact`}}}}function RD(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 zD(...e){for(let t of e)if(!RD(t))return t}function BD(e,t){return RD(t)?e:t}function VD(e){return JSON.parse(e)}function HD(e,t,n){return cT(n)?e:t}function UD(e){return JSON.stringify(e)??`null`}function WD(e){return JSON.stringify(e,null,2)??`null`}function GD(){return{default:{fn:(e,t)=>BD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>RD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>zD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>HD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>VD(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>UD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>WD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function KD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function qD(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 KD(...t)}function JD(e,t){return e[t]}function YD(e,t){return t in e}function XD(e){return Object.keys(e)}function ZD(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 QD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function $D(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 eO(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function tO(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function nO(e,t,n){return e[t]=n,e}function rO(e,t){return delete e[t],e}function iO(e){return Object.values(e)}function aO(){return{dict:{fn:(...e)=>KD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>JD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>nO(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>rO(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>XD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>iO(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>tO(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>eO(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>$D(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>YD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>ZD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>QD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function oO(e){throw new vw(e)}function sO(){return{fail:{fn:e=>oO(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 cO(...e){for(let t of e)if(RD(t))return!1;return!0}function lO(...e){for(let t of e)if(!RD(t))return!0;return!1}function uO(e,t){return[...e,t]}function dO(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 fO(e){return e.filter(e=>!RD(e))}function pO(...e){let t=[];for(let n of e)t.push(...n);return t}const mO={line:0,column:0,offset:0};function hO(e,t,n,r){return new hw(e,t,n,r,mO)}function gO(...e){if(e.length<3)throw hO(`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(!vO(t))throw hO(`dig`,e.length-1,`dict`,yO(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw hO(`dig`,e,`string`,yO(r[e]));return _O(t,n,r,e.length)}function _O(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(!vO(a))throw hO(`dig`,r-1,`dict at intermediate key`,yO(a));return _O(a,t,n.slice(1),r)}function vO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function yO(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function bO(e){return e[0]}function xO(e,t){return t.some(t=>iT(t,e))}function SO(e){return e.slice(0,-1)}function CO(e){return e[e.length-1]}function wO(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function TO(...e){return e}function EO(e,t){return[t,...e]}function DO(e){return e.slice(1)}function OO(e){return[...e].reverse()}function kO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function AO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function jO(e){let t=[];for(let n of e)t.some(e=>iT(e,n))||t.push(n);return t}function MO(e,...t){return e.filter(e=>!t.some(t=>iT(t,e)))}function NO(){return{list:{fn:(...e)=>TO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>bO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>CO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>DO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>SO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>wO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>OO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>jO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>MO(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>xO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>fO(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>kO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>pO(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>dO(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>EO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>uO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>AO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>uO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>TO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>gO(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>cO(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>lO(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function PO(...e){return e.reduce((e,t)=>e+t,0)}function FO(e){return e+1}function IO(e){return e+1}function LO(...e){return e.reduce((e,t)=>e+t,0)}function RO(e){return Math.ceil(e)}function zO(e,t){return Math.trunc(e/t)}function BO(e,...t){return t.reduce((e,t)=>e/t,e)}function VO(e){return Math.floor(e)}function HO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function UO(...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 GO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function KO(e,t){return e%t}function qO(...e){return e.reduce((e,t)=>e*t,1)}function JO(...e){return e.reduce((e,t)=>e*t,1)}function YO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function XO(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 ZO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),XO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return XO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:XO(n,i+t,r).join(` `)}default:return``}}function QO(e,t){return e-t}function $O(e,...t){return t.reduce((e,t)=>e-t,e)}function ek(e){return XO(0,e,e<0?-1:1)}function tk(){return{add:{fn:(...e)=>PO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>QO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>qO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>zO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>KO(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)=>HO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>VO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>RO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>YO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>LO(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>$O(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>JO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>BO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>FO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>IO(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>UO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>GO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>HO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>ZO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>ek(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>XO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function nk(e){return Array.from(e)}function rk(e,t){return e===``?nk(t):t.split(e)}function ik(e,t){let n=nk(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function ak(e,t,n){let r=nk(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const ok={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},sk=/^[-_\s]$/,ck=/^\p{P}$/u,lk=/^\p{L}$/u,uk=/^\p{Lu}$/u,dk=/^\p{N}$/u;function fk(e){return e!==void 0&&sk.test(e)}function pk(e){return e!==void 0&&lk.test(e)}function mk(e){return e!==void 0&&uk.test(e)}function hk(e){return e!==void 0&&dk.test(e)}function gk(e){return e!==void 0&&ck.test(e)}function _k(e,t){if(t>=e.length)return{word:{wt:ok.Invalid,text:``},next:t};let n=e[t],r=t+1;if(fk(n)){for(;r<e.length&&fk(e[r]);)r++;return{word:{wt:ok.Connector,text:e.slice(t,r).join(``)},next:r}}if(gk(n)){for(;r<e.length&&gk(e[r]);)r++;return{word:{wt:ok.Punct,text:e.slice(t,r).join(``)},next:r}}if(mk(n)){if(r>=e.length)return{word:{wt:ok.UpperCase,text:n},next:r};if(mk(e[r])){let n=r;for(;n<e.length&&mk(e[n]);)n++;return n<e.length&&pk(e[n])?{word:{wt:ok.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:ok.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(pk(e[r])){let n=r+1;for(;n<e.length&&pk(e[n])&&!mk(e[n]);)n++;return{word:{wt:ok.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:ok.UpperCase,text:n},next:r}}if(pk(n)){for(;r<e.length&&pk(e[r])&&!mk(e[r]);)r++;return{word:{wt:ok.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(hk(n)){for(;r<e.length&&hk(e[r]);)r++;return{word:{wt:ok.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!fk(e[r])&&!pk(e[r])&&!hk(e[r])&&!gk(e[r]);)r++;return{word:{wt:ok.Other,text:e.slice(t,r).join(``)},next:r}}function vk(e,t,n){if(t.wt!==ok.UpperCase&&t.wt!==ok.Connector){e.push(t.text);return}for(let r of t.text)fk(r)?e.push(n):mk(r)?e.push(r.toLowerCase()):e.push(r)}function yk(e,t){if(e.length===0)return``;let n=nk(e),r=[],{word:i,next:a}=_k(n,0);for(;a<n.length;){i.wt!==ok.Connector&&vk(r,i,t);let e=i,o=i;if({word:i,next:a}=_k(n,a),e.wt===ok.Number){for(;i.wt===ok.Alphabet||i.wt===ok.Number;)vk(r,i,t),{word:i,next:a}=_k(n,a);i.wt!==ok.Invalid&&i.wt!==ok.Punct&&i.wt!==ok.Connector&&r.push(t);continue}if(e.wt===ok.Connector){vk(r,o,t);continue}if(e.wt===ok.Punct)continue;if(i.wt!==ok.Number){i.wt!==ok.Connector&&i.wt!==ok.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=_k(n,a),i.wt!==ok.Alphabet){vk(r,s,t),i.wt!==ok.Connector&&i.wt!==ok.Punct&&r.push(t);continue}for(r.push(t),vk(r,s,t);i.wt===ok.Alphabet||i.wt===ok.Number;)vk(r,i,t),{word:i,next:a}=_k(n,a);i.wt!==ok.Invalid&&i.wt!==ok.Connector&&i.wt!==ok.Punct&&r.push(t)}return vk(r,i,t),r.join(``).toLowerCase()}function bk(e){if(e.length===0)return``;let t=nk(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!fk(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++,fk(i)&&fk(e)){n.push(e);continue}fk(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function xk(e){return bk(e)}function Sk(...e){return e.join(` `)}function Ck(e,t){return t.includes(e)}function wk(e,t){return t.startsWith(e)}function Tk(e,t){return t.endsWith(e)}function Ek(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 cA(e,t,n){return sA(e,t,n)}function lA(){return{abbrev:{fn:(e,t)=>sk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>ck(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>wk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>Tk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>Ek(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>Dk(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)=>kk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>Ak(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>jk(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>Nk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>Pk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>Fk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>Ik(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>Lk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Rk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>zk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Bk(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=>Hk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>Uk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Wk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Gk(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>qk(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Jk(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>Yk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Qk(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>$k(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>eA(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>tA(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>nA(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>rA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>iA(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>aA(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>oA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>cA(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function uA(e,t){let n=dA(e),r=n.copy();return r.style=nf(n.style,t),r}function dA(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 fA(e){return{fn:(t=>uA(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function pA(e){return{fn:((t,n)=>uA(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function mA(e,t){return new W({[e]:t})}function hA(){let e={};for(let t of Jd)e[t]=fA(mA(t,!0)),e[`not_${t}`]=fA(mA(t,!1));for(let[t,n]of Object.entries(Xd))e[t]=fA(mA(n,!0));return e}const gA={fn:((e,t)=>uA(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},_A={fn:((e,t)=>uA(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function vA(){return{fg:pA(`color`),bg:pA(`bgcolor`),...hA(),link:_A,style:gA}}function yA(e,t){let n;try{n=Hl(e.trim())}catch(n){throw n instanceof wl?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 bA(n,t,JSON.stringify(e))}function bA(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 xA(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function SA(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 CA=xA([`string`,`int`],((e,t)=>Au(yA(e,`darken`),t).hex)),wA=xA([`string`,`int`],((e,t)=>Au(yA(e,`lighten`),-t).hex)),TA={min:0,max:100,note:`0 = from, 100 = toward`},EA=xA([`string`,`string`,`float`],((e,t,n)=>Ul(yA(e,`mix`),yA(t,`mix`),SA(n,`mix`,`percentage`,TA)/100).hex)),DA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},OA=xA([`string`],(e=>Fu(yA(e,`contrastOn`)).hex)),kA={depth:H.TRUECOLOR},AA=e=>xA([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Iu(yA(t,`readableOn`),yA(n,`readableOn`),SA(r,`readableOn`,`ratio`,DA),i,void 0,a).hex})),jA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function MA(){let e={};for(let[t,n]of Object.entries(jA)){let r=t;e[n]=xA([`string`,`float`],((e,t)=>{let i={...cu,[r]:SA(t,n,`amount`)};return bu.fromRgba(yA(e,n)).applyKey(i).toRgba().hex}))}return e}function NA(e=()=>kA){return{darken:CA,lighten:wA,mix:EA,contrastOn:OA,readableOn:AA(e),...MA()}}function PA(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:bA(wu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function FA(e){return{color:{fn:(t=>wu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Xf(Nd(n),PA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const IA=rp.play(0);function LA(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 RA={...wg.loops,typewriter:e=>wg.transitions.typewriter(e).effect,scramble:e=>wg.transitions.scramble(e).effect,backspace:e=>wg.transitions.backspace(e).effect,scrambleOut:e=>wg.transitions.scrambleOut(e).effect};function zA(e){if(!Object.hasOwn(RA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(RA).map(e=>JSON.stringify(e)).join(`, `)}`);return RA[e]}function BA(e,t={}){let n=t.timeline??(()=>IA),r=(e,t,r)=>[rp.run(n(),t),Ld(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=zf(a,o,i);return i.onHold?.(Bf(s,o)),s.value},a=(e,t)=>rp.run(rp.play(e),t);return{frames:{fn:((...t)=>{let n=LA(`frame`,t,dA).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return Eg(...r(`frames`,new Tg(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=LA(`color`,e,e=>yA(e,`stepped`));return t[i(`stepped`,Ud(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,Yf(r,o,{seconds:e,ease:Nd(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Wd.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=zA(t),s=dA(i),c=s.plain,l=e();return Eg(...r(`glyphs`,a(n,ng(s,o({z:qm(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function VA(e){return{...vA(),...NA(e)}}new W({color:`red`,dim:!0});const HA=/^(?:(?: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,UA=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function WA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(HA);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(UA);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 GA(e){let t=e.match(UA);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 KA(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 qA(e){return e.toLocaleString()}function JA(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 YA(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 XA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],ZA=XA.length;function QA(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*(ZA-1));o+=XA[t]}return o}function $A(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 ej(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 tj=cv(),nj=[...Av];function rj(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>KA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(XC(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>YC(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>ZC(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>tj,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>nj,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ej(`sparkline`,[`width`],n),QA($A(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>YA(e,JA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function ij(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 aj=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)=>ij(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function oj(){return{formatInteger:{fn:e=>qA(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>WA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>GA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let sj=null;function cj(e,t){if(sj!==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 sj=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{sj=null}}}function lj(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(sj===null)throw Error(`the clock was read outside a draw (${e})`);return sj}const uj={now:()=>lt(lj(`now`).at),frame:()=>lj(`frame`).frame,timeline:()=>lj(`timeline`).timeline};function dj(e,t){let{frames:n,stepped:r}=BA(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 fj=new Set([`now`,`ago`]);function pj(e,t){return Object.fromEntries(Object.entries(BD(e)).filter(([e])=>fj.has(e)===t))}const mj=pj(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),hj=[e=>pj(e.now,!0),e=>dj(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(dj(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),aj];function gj(e){return Object.assign({},...e.map(e=>e(uj)))}const _j=new Set(Object.keys(gj(hj)));function vj(e){return new Set([..._j,...Object.keys(gj(e))])}function yj(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return aE({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...JD(),...lA(),...IO(),...ik(),...AE(),...uO(),...cO(),...mj,...VA(r),readableOn:AA(r),...gj([...hj,...e.clockFuncs??[]]),...rj(),...oj(),...n??{}}})}function bj(e){return xj(e,new Set(e.names()),``)}function xj(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!Cj(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:wj(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return xj(e,t,a)}})}function Sj(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 Cj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function wj(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new QC(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var Tj=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 Ej(e,t){let{dir:n,rest:r}=An(e,s.dirname(t));return{dir:n,name:r[0]??s.basename(t),leaf:r.length===0}}const Dj=(e,t)=>Pe(t);function Oj(e,t){let n=[],r=!0,i=new Map;for(let a of t.named){let{hops:t,stopped:o}=cr(e,a);o!==null&&n.push({path:a,reason:o.message});for(let n of t){let{dir:t,name:a,leaf:o}=Ej(e,n);r&&=o;let s=i.has(t)?i.get(t):new Set;s?.add(a),i.set(t,s)}}for(let n of t.whole.map(t=>kn(e,t)))n!==null&&i.set(n,null);let a={dirs:[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},o=new Map(a.dirs.map(t=>{let n=xc(e,t.path);return[t.path,Cc(n)?Sc(n):null]}));return{key:JSON.stringify([a,[...o]]),targets:a,unbound:[...o.values()].includes(null),bound:o,reached:r,unresolved:n}}function kj(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 Aj(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 jj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([s.join(e,t)])},Mj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),Nj=(e,t)=>e.kind===`listening`&&e.handle===t,Pj=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var Fj=class{slots=new Map;dirs=new Map;counters;logger;clock;filesystem;closed=!1;constructor(e){this.clock=e.clock,this.filesystem=e.filesystem,this.counters=e.counters,this.logger=e.logger??Dj}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=Pj(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=xc(this.filesystem,e.path);Cc(n)&&Sc(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,Mj(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Sc(xc(this.filesystem,i));try{this.filesystem.opendirSync(i);let r=this.filesystem.watch(i,{recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.onError(e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!Nj(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,Mj(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(!Nj(r,t))return;let i=n===s.basename(e.path)&&Sc(xc(this.filesystem,e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,jj(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=Aj(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 Ij(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function kte(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var Lj=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 Rj(){return X.observable.box(zj(`unread`),{deep:!1})}function zj(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function Bj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,X.compareStructural)(n,t)||((0,X.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Vj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,X.runInAction)(()=>e.reading.set({...n,why:t})):(0,X.runInAction)(()=>e.reading.set(zj(t)))}function Hj(e,t){e.reading.get().kind===`pending`&&Bj(e,t)}function Uj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function Wj(e){return e.reading.get()}async function Gj(e){for(;;){let t=e();if(!Uj(t))return t;await t.landed}}function Kj(e,t,n,r){let i=new AbortController,a=()=>i.abort(),o=t>0?r(t,a):qj(a);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(()=>{o(),i.abort()})}function qj(e){return Promise.resolve().then(()=>process.nextTick(e)),()=>{}}function Jj(e){return{current:()=>e}}const Yj=()=>()=>{};var Xj=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 Jj(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>Wj(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Vj(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:Rj(),holders:0,flight:null,changed:!1,superseding:0,revisit:Zj(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();$j(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=tt(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{Bj(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(),Hj(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function Zj(e,t,n){if(e===null)return new Qj(n.holdReturned);let r=new Lj(n.period,t);return{landed:t=>r.landed(Ij(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var Qj=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 $j(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const eM=[`first`,`period`,`change`,`request`,`supersede`];var tM=class{tallies=new Map;constructor(e=Ie){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 rM(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(eM.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of eM)e[n]+=t.refreshes[n]??0;return e}};const nM={first:!0,period:!0,change:!0,request:!1,supersede:!0};var rM=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&&!nM[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`)}};const iM=/\r\n|\r|\n/g,aM=e=>F(e.replace(iM,` `).trim());function oM(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(iM,` `))}}const sM=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},cM=e=>Gv(e);function lM(e){return se.createHash(`sha256`).update(e).digest(`hex`)}const uM=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function dM(e,t,n,r){return{where:uM({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${vt(i,` in ${n}`)}`,`read`)}}}function fM(e,t,n){return{where:uM({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await he(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function pM(e,t,n){switch(t.kind){case`shell`:return dM(e,t.command,t.cwd,n);case`file`:return fM(t.path,t.readMode,n)}}function mM(e){switch(e.kind){case`text`:return aM;case`regex`:return oM(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:sM(e)}}function hM(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var gM=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=_M(this.watchers.filesystem,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=_M(this.watchers.filesystem,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 kj(`watch_file ${e}`,t.bound,Ac(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const _M=(e,t)=>Oj(e,{named:[t],whole:[t]}),vM={declare:(e,t)=>({digest:cM(t),current:()=>so(`unread`),fault:()=>null})},yM={declare:(e,t)=>{throw Error(`a directory declares no shell or file source, and ${uM(t.read)} was declared in one: each is a session view's`)}};var bM=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Ie,n=e.ledger??new tM(t);this.watchMgr=new gM(e.watchers??new Fj({filesystem:Pn,clock:e.clock}),e.fileEvents??Tc);let r=r=>new Xj({name:`source.${r}`,scope:`daemon`,keyOf:cM,fields:(e,t)=>`digest=${Cn(cM(e))} where=${z(uM(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=pM(e.launcher,t.read,n);return hM(await r.read(),mM(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 Yj();let n=cM(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,X.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,X.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=cM(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 xM(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(Pe(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function SM(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 CM=`session.id`;function wM(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 TM={read:()=>so(`unread`),drawnAt:()=>{throw new QC(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},EM=e=>({kind:`found`,value:e});function DM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&co(n))return n;if(typeof n!=`object`||!n)return EM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&co(n)?n:EM(n)}function OM(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function kM(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`?YC(e):t===`number`?XC(e):ZC(e)}function AM(e){return e===`number`?0:e===`boolean`?!1:``}var jM=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];holds=new Tj;identities=new Map;lanes=X.observable.map(void 0,{deep:!1});inputs=X.observable.box(TM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=yj({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t,n=``,r,i=null){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.sessionState=r}view(t){return new e(t,new fw(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,JC(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>OM(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 QC(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=kM(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},xM(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,X.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,X.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:wM(r),refresh:n}))}hold(e,t){(0,X.runInAction)(()=>{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]}));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,ao(t,n))}}documentPublisher(e,t){let n=t===void 0?so(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(it(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(bj(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=kM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=$C(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(CM);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(CM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.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,X.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(bj(this.store)).map(e=>e.plain).join(``))}catch(e){return $C(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):so(`unread`)}},e=>n({kind:`key`,hash:lM(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`)?F(e.map(e=>e.value).join(`,`)):so(`unread`)},e=>n({kind:`key`,hash:lM(e)}));break}}onReads(e,t,n){let r,i=(0,X.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 kM(this.defaultEmptyValue,t)}catch{return AM(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function MM(e,t){let n=Xb[e],r=rx(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 NM=Object.fromEntries([...lx].map(([e,t])=>[t,MM(e,t)])),PM={subscribers:`number`,fps:`number`,shown:`boolean`},FM=Object.keys(PM),IM={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[CM]:{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:``},...NM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(gb.flatMap(e=>FM.map(t=>[xb(e,t),{kind:`input`,path:xb(e,t),type:PM[t],default:bb[t]}]))),[yb(`by`)]:{kind:`input`,path:yb(`by`),default:vb.by},[yb(`fps`)]:{kind:`input`,path:yb(`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:``}},LM={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 RM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(LM,t)?t:void 0}const zM=Object.fromEntries(pv.map(e=>[e,lx.get(e)]));function BM(e){return pv.find(t=>zM[t]===e)}function VM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of CC(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 $v(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(CM);for(let t of Object.values(e.actions)){r.add(CM);for(let[,e]of Yx(t))i(e);let e=`set`in t?ux.get(t.set):void 0,n=`persist`in t?lx.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function HM(e,t,n){let r=HC({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of VM(e,t,n.helpers)){if(VC(a,r))continue;let e=IM[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 UM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function WM(e){return e}function GM(e,t,n){return n===void 0?Qx+UM(e)+`.`+UM(t):KM(n)}function KM(e){return Qx+UM(e)}function qM(e,t){return e+`.`+t}function JM(e){return $x+e}const YM=[`closeOnPick`,`paged`,`key`,`distribution`],XM=e=>YM.includes(e),ZM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${g_.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function QM(e){for(let t of Object.keys(e))if(!XM(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${ZM}`);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&&!__(r))throw Error(`{{ menu }} option "distribution" must be one of: ${g_.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:y_(r)}}const $M=e=>`from`in e?e.from:e.themes;function eN(e,t,n){return e===`bool`?Hv(t)!==null:`min`in e?Uv(t,e)!==null:Gx($M(e),n).members.includes(t)}function tN(e,t){if(e===`bool`)return Bv.join(` or `);if(!(`min`in e)){let n=$M(e),{members:r}=Gx(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 nN(e){return{label:e.label,domain:rN(e.domain)}}function rN(e){return e===`theme`?{themes:Ux}:e===`bool`||`min`in e?e:{from:e}}function iN(e,t,n,r,i){let a=aa(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Bv]}},variables:{}};if(`from`in o)return aN(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 aN(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 aN(e,t,n,r,i){let a={variable:n,key:n,member:t},o=qM(n,t),s=`${t}.open`,c=JM(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]:pa(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:fa(n,ea),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const oN=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],sN=Object.fromEntries(oN.map(e=>[e.member,e.label])),cN={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},lN=Object.keys(cN),uN=dx(e=>ax[e].place),dN=e=>Object.hasOwn(cN,e),fN=(e,t)=>e===t||dN(e)&&fN(uN[cN[e].beside],t),pN=e=>dN(e)?`${pN(uN[cN[e].beside])} › ${cN[e].trigger}`:e===`door`?`first line`:sN[e],mN=e=>pN(uN[e]),hN=()=>[`door`,...oN.map(e=>e.member)].flatMap(e=>[e,...lN.filter(t=>fN(t,e))]).map(e=>({path:pN(e),names:ox.filter(t=>uN[t]===e)})).filter(({names:e})=>e.length>0),gN=e=>{let{setting:t,on:n,inTmux:r}=hb[e].switch;return`${hb[e].label} is off — turn it on in the settings menu's ${mN(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},_N=Object.fromEntries(Object.entries(Xb).map(([e,t])=>[e,t.spec]));function vN(e){return yN(Xb[e])}function yN(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function bN(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 xN(e){return bN(`${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 SN(e){return bN(`${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 CN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&mv(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 wN={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 ${mN(`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."},TN={noun:`globals key`,fields:_N,removed:wN},EN={preset:xN(`a preset`),menuGlyph:SN(`a preset`)},DN={noun:`preset globals key`,fields:{..._N,...EN},removed:wN};function ON(e){return RN(e)&&!(e in EN)}const kN=`is decided later than any rule could be settled`,AN={noun:`editGlobals key`,removed:wN,fields:{..._N,preset:xN(`the editGlobals fragment`),menuGlyph:SN(`the editGlobals fragment`),palette:CN(_N.palette,`the editGlobals fragment`,kN),style:CN(_N.style,`the editGlobals fragment`,kN),effect:CN(_N.effect,`the editGlobals fragment`,kN)}},jN={noun:`theme default key`,fields:{...Object.fromEntries(ex.map(e=>[e,_N[e]])),style:CN(_N.style,`a theme's default`,`is the look that theme wears by name`)}};function MN(e,t){if(!Wv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Vy(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${av(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=Hy(e,jN,t,i);a!==null&&(n[r]=a)}return n}function NN(e,t,n){return n===void 0?{}:Hy(e,TN,t,n)??{}}function PN(e,t,n){return Hy(e,DN,t,n)??{}}function FN(){return lb(DN)}function IN(e,t,n){return Hy(e,AN,t,n)??{}}const LN=new Set(Object.keys(_N));function RN(e){return LN.has(e)}function zN(e){return Object.hasOwn(wN,e)?wN[e]:void 0}function BN(){return[...LN]}const VN=new Map(Object.entries(Xb).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function HN(e){let t=new Map;for(let[n,r]of VN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const UN=/^segments\.([^.]+)\.palette$/,WN=/^presets\.(.+)\.root$/,GN=/^presets\.(.+)\.globals\.([^.]+)$/,KN=/^themeDefaults\.(.+)\.([^.]+)$/;function qN(e){return`presets.${e}.root`}function JN(e,t){return`themeDefaults.${e}.${t}`}const YN=e=>ex.includes(e);function XN(e,t){return`presets.${e}.globals.${t}`}function ZN(e){if(RN(e))return{scope:`globals`,field:e};let t=UN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=GN.exec(e);if(n&&ON(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=KN.exec(e);if(r&&YN(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 QN(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 $N=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],eP=[...$N,`other`],tP={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},nP=aE({fromString:e=>e});function rP(e){let t=UM(e);return nS.find(e=>t.startsWith(UM(e)))}function iP(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 aP(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=oC(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=oC(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 oP=`edit.mode`,sP=`edit.configure`,cP=`edit.toggle`,lP=`arrange`,uP=`${eS}draft.`;function dP(e,t){return`${e}:${t}`}const fP={variable:oP,key:oP,member:lP},pP=sa(fP);function Ate(e){try{return nP.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function jte(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`&&Ate(t))return!0}return!1}function Mte(e,t){if(iP(e,t,eS,`edit mode`),!jte(t))return;let{variables:n,actions:r}=mP();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function mP(){return{variables:{[oP]:{...fa(oP,ea),within:[oS]},[sP]:{...fa(sP,ea),within:[fP]}},actions:{[cP]:pa(oP,lP),"edit.unconfigure":{set:sP,to:ea}}}}function hP(e,t,n,r){let i={variable:e,key:e,member:ta};return r.variables[e]={...fa(e,ea),...n.length>0&&{within:n}},r.actions[e]=pa(e,ta),r.segments[e]={template:la(e,`(?)`,`✕`),...Nte(n)},oa(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 Nte(e){let[t,...n]=e;return t===void 0?{}:{when:sa(t,...n)}}const gP=`none`;function _P(e){return wu(e,`background`)}var Pte=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Fte(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=vP(n,i),l=c!==gP,u=l?c===void 0?o:yP(a,c,`bg`):_P(a);e.bg=u;let d=vP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:F_(a,e,t))(u):void 0:yP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function vP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function yP(e,t,n){try{return wu(e,t)}catch(e){throw e instanceof Cu?new Pte(t,n,e.message):e}}const bP=`🔧`,xP={help:[`-h`,`--help`],version:[`-V`,`--version`]},SP=[...new Set(Object.values(hb).map(e=>mN(e.switch.setting)))].join(` or `),Ite=Math.max(...Object.values(ax).map(e=>e.configKey.length))+2,CP=[`✚ inserts`,`✖ removes`,`${bP} configures`,`↺ resets layout`],wP={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`]},Lte=`
|
|
68
|
+
`)}function Dk(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 Ok(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw hO(`join`,2,`list of strings/primitives`,`list element of type ${kk(e)}`);n.push(String(e))}return n.join(e)}function kk(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Ak(e){return yk(e,`-`)}function jk(e){return e.toLowerCase()}function Mk(e,t){return`\n${Ek(e,t)}`}function Nk(e){return e.replace(/\s+/g,``)}function Pk(e,t,n){return n===1?e:t}function Fk(...e){return e.map(e=>`"${e}"`).join(` `)}function Ik(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Lk(e,t){return t.repeat(Math.max(0,e))}function Rk(e,t,n){return rk(e,n).join(t)}function zk(e){return yk(e,`_`)}function Bk(e,t){let n=rk(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Vk(e,t){return rk(e,t)}function Hk(e,t,n){let r=Uk(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Uk(e,t,n){if(n===0)return[];let r=rk(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 Wk(...e){return e.map(e=>`'${e}'`).join(` `)}function Gk(e,t,n){let r=nk(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 Kk(e){let t=``;for(let n of e)qk(n)?t+=n.toLowerCase():Jk(n)?t+=n.toUpperCase():t+=n;return t}function qk(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function Jk(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Yk(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Xk(e){return e.trim()}function Zk(e,t){if(e.length===0)return t;let n=new Set(nk(e)),r=nk(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 Qk(e,t){return t.startsWith(e)?t.slice(e.length):t}function $k(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function eA(e,t){let n=nk(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 tA(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function nA(e){return e.toUpperCase()}function rA(e,t){return iA(e,`
|
|
69
|
+
`,t)}function iA(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 aA(e,t,n){return iA(e,t,n)}function oA(){return{abbrev:{fn:(e,t)=>ik(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>ak(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>xk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>Sk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>Ck(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>wk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>Tk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>Ek(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>Dk(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>Ok(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>Ak(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>jk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>Mk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>Nk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>Pk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Fk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>Ik(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Lk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Rk(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>zk(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)=>Vk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Hk(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)=>Gk(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>Kk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Yk(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Xk(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Zk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>Qk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>$k(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>eA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>tA(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>nA(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>rA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>aA(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function sA(e,t){let n=cA(e),r=n.copy();return r.style=nf(n.style,t),r}function cA(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 lA(e){return{fn:(t=>sA(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function uA(e){return{fn:((t,n)=>sA(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function dA(e,t){return new W({[e]:t})}function fA(){let e={};for(let t of Jd)e[t]=lA(dA(t,!0)),e[`not_${t}`]=lA(dA(t,!1));for(let[t,n]of Object.entries(Xd))e[t]=lA(dA(n,!0));return e}const pA={fn:((e,t)=>sA(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},mA={fn:((e,t)=>sA(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function hA(){return{fg:uA(`color`),bg:uA(`bgcolor`),...fA(),link:mA,style:pA}}function gA(e,t){let n;try{n=Hl(e.trim())}catch(n){throw n instanceof wl?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 _A(n,t,JSON.stringify(e))}function _A(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 vA(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function yA(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 bA=vA([`string`,`int`],((e,t)=>Au(gA(e,`darken`),t).hex)),xA=vA([`string`,`int`],((e,t)=>Au(gA(e,`lighten`),-t).hex)),SA={min:0,max:100,note:`0 = from, 100 = toward`},CA=vA([`string`,`string`,`float`],((e,t,n)=>Ul(gA(e,`mix`),gA(t,`mix`),yA(n,`mix`,`percentage`,SA)/100).hex)),wA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},TA=vA([`string`],(e=>Fu(gA(e,`contrastOn`)).hex)),EA={depth:H.TRUECOLOR},DA=e=>vA([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Iu(gA(t,`readableOn`),gA(n,`readableOn`),yA(r,`readableOn`,`ratio`,wA),i,void 0,a).hex})),OA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function kA(){let e={};for(let[t,n]of Object.entries(OA)){let r=t;e[n]=vA([`string`,`float`],((e,t)=>{let i={...cu,[r]:yA(t,n,`amount`)};return bu.fromRgba(gA(e,n)).applyKey(i).toRgba().hex}))}return e}function AA(e=()=>EA){return{darken:bA,lighten:xA,mix:CA,contrastOn:TA,readableOn:DA(e),...kA()}}function jA(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:_A(wu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function MA(e){return{color:{fn:(t=>wu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Xf(Nd(n),jA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const NA=rp.play(0);function PA(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 FA={...Sg.loops,typewriter:e=>Sg.transitions.typewriter(e).effect,scramble:e=>Sg.transitions.scramble(e).effect,backspace:e=>Sg.transitions.backspace(e).effect,scrambleOut:e=>Sg.transitions.scrambleOut(e).effect};function IA(e){if(!Object.hasOwn(FA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(FA).map(e=>JSON.stringify(e)).join(`, `)}`);return FA[e]}function LA(e,t={}){let n=t.timeline??(()=>NA),r=(e,t,r)=>[rp.run(n(),t),Ld(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=zf(a,o,i);return i.onHold?.(Bf(s,o)),s.value},a=(e,t)=>rp.run(rp.play(e),t);return{frames:{fn:((...t)=>{let n=PA(`frame`,t,cA).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return wg(...r(`frames`,new Cg(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=PA(`color`,e,e=>gA(e,`stepped`));return t[i(`stepped`,Ud(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,Yf(r,o,{seconds:e,ease:Nd(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Wd.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=IA(t),s=cA(i),c=s.plain,l=e();return wg(...r(`glyphs`,a(n,eg(s,o({z:Km(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function RA(e){return{...hA(),...AA(e)}}new W({color:`red`,dim:!0});const zA=/^(?:(?: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 VA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(zA);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 HA(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 UA(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 GA(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 KA(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 qA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],JA=qA.length;function YA(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*(JA-1));o+=qA[t]}return o}function XA(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 ZA(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 QA=ov(),$A=[...Ov];function ej(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>UA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(qC(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>KC(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>JC(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>QA,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>$A,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ZA(`sparkline`,[`width`],n),YA(XA(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>KA(e,GA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function tj(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 nj=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)=>tj(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function rj(){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=>VA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>HA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let ij=null;function aj(e,t){if(ij!==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 ij=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{ij=null}}}function oj(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(ij===null)throw Error(`the clock was read outside a draw (${e})`);return ij}const sj={now:()=>lt(oj(`now`).at),frame:()=>oj(`frame`).frame,timeline:()=>oj(`timeline`).timeline};function cj(e,t){let{frames:n,stepped:r}=LA(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 lj=new Set([`now`,`ago`]);function uj(e,t){return Object.fromEntries(Object.entries(LD(e)).filter(([e])=>lj.has(e)===t))}const dj=uj(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),fj=[e=>uj(e.now,!0),e=>cj(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(cj(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),nj];function pj(e){return Object.assign({},...e.map(e=>e(sj)))}const mj=new Set(Object.keys(pj(fj)));function hj(e){return new Set([...mj,...Object.keys(pj(e))])}function gj(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return nE({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...GD(),...oA(),...NO(),...tk(),...DE(),...sO(),...aO(),...dj,...RA(r),readableOn:DA(r),...pj([...fj,...e.clockFuncs??[]]),...ej(),...rj(),...n??{}}})}function _j(e){return vj(e,new Set(e.names()),``)}function vj(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!bj(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:xj(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return vj(e,t,a)}})}function yj(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 bj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function xj(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new YC(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var Sj=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 Cj(e,t){let{dir:n,rest:r}=An(e,s.dirname(t));return{dir:n,name:r[0]??s.basename(t),leaf:r.length===0}}const wj=(e,t)=>Pe(t);function Tj(e,t){let n=[],r=!0,i=new Map;for(let a of t.named){let{hops:t,stopped:o}=cr(e,a);o!==null&&n.push({path:a,reason:o.message});for(let n of t){let{dir:t,name:a,leaf:o}=Cj(e,n);r&&=o;let s=i.has(t)?i.get(t):new Set;s?.add(a),i.set(t,s)}}for(let n of t.whole.map(t=>kn(e,t)))n!==null&&i.set(n,null);let a={dirs:[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},o=new Map(a.dirs.map(t=>{let n=xc(e,t.path);return[t.path,Cc(n)?Sc(n):null]}));return{key:JSON.stringify([a,[...o]]),targets:a,unbound:[...o.values()].includes(null),bound:o,reached:r,unresolved:n}}function Ej(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 Oj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([s.join(e,t)])},kj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),Aj=(e,t)=>e.kind===`listening`&&e.handle===t,jj=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var Mj=class{slots=new Map;dirs=new Map;counters;logger;clock;filesystem;closed=!1;constructor(e){this.clock=e.clock,this.filesystem=e.filesystem,this.counters=e.counters,this.logger=e.logger??wj}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=jj(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=xc(this.filesystem,e.path);Cc(n)&&Sc(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,kj(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Sc(xc(this.filesystem,i));try{this.filesystem.opendirSync(i);let r=this.filesystem.watch(i,{recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.onError(e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!Aj(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,kj(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(!Aj(r,t))return;let i=n===s.basename(e.path)&&Sc(xc(this.filesystem,e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,Oj(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 Nj(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function Mte(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var Pj=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 Fj(){return X.observable.box(Ij(`unread`),{deep:!1})}function Ij(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function Lj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,X.compareStructural)(n,t)||((0,X.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Rj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,X.runInAction)(()=>e.reading.set({...n,why:t})):(0,X.runInAction)(()=>e.reading.set(Ij(t)))}function zj(e,t){e.reading.get().kind===`pending`&&Lj(e,t)}function Bj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function Vj(e){return e.reading.get()}async function Hj(e){for(;;){let t=e();if(!Bj(t))return t;await t.landed}}function Uj(e,t,n,r){let i=new AbortController,a=()=>i.abort(),o=t>0?r(t,a):Wj(a);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(()=>{o(),i.abort()})}function Wj(e){return Promise.resolve().then(()=>process.nextTick(e)),()=>{}}function Gj(e){return{current:()=>e}}const Kj=()=>()=>{};var qj=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 Gj(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>Vj(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Rj(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:Fj(),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();Xj(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=tt(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{Lj(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(),zj(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function Jj(e,t,n){if(e===null)return new Yj(n.holdReturned);let r=new Pj(n.period,t);return{landed:t=>r.landed(Nj(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var Yj=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 Xj(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const Zj=[`first`,`period`,`change`,`request`,`supersede`];var Qj=class{tallies=new Map;constructor(e=Ie){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 eM(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(Zj.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Zj)e[n]+=t.refreshes[n]??0;return e}};const $j={first:!0,period:!0,change:!0,request:!1,supersede:!0};var eM=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&&!$j[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`)}};const tM=/\r\n|\r|\n/g,nM=e=>F(e.replace(tM,` `).trim());function rM(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(tM,` `))}}const iM=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},aM=e=>Uv(e);function oM(e){return se.createHash(`sha256`).update(e).digest(`hex`)}const sM=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function cM(e,t,n,r){return{where:sM({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${vt(i,` in ${n}`)}`,`read`)}}}function lM(e,t,n){return{where:sM({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await he(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function uM(e,t,n){switch(t.kind){case`shell`:return cM(e,t.command,t.cwd,n);case`file`:return lM(t.path,t.readMode,n)}}function dM(e){switch(e.kind){case`text`:return nM;case`regex`:return rM(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:iM(e)}}function fM(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var pM=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=mM(this.watchers.filesystem,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=mM(this.watchers.filesystem,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 Ej(`watch_file ${e}`,t.bound,Ac(this.fileEvents.delivery()))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const mM=(e,t)=>Tj(e,{named:[t],whole:[t]}),hM={declare:(e,t)=>({digest:aM(t),current:()=>so(`unread`),fault:()=>null})},gM={declare:(e,t)=>{throw Error(`a directory declares no shell or file source, and ${sM(t.read)} was declared in one: each is a session view's`)}};var _M=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Ie,n=e.ledger??new Qj(t);this.watchMgr=new pM(e.watchers??new Mj({filesystem:Pn,clock:e.clock}),e.fileEvents??Tc);let r=r=>new qj({name:`source.${r}`,scope:`daemon`,keyOf:aM,fields:(e,t)=>`digest=${Cn(aM(e))} where=${z(sM(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=uM(e.launcher,t.read,n);return fM(await r.read(),dM(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=aM(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,X.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,X.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=aM(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 vM(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(Pe(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yM(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 bM=`session.id`;function xM(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 SM={read:()=>so(`unread`),drawnAt:()=>{throw new YC(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},CM=e=>({kind:`found`,value:e});function wM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&co(n))return n;if(typeof n!=`object`||!n)return CM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&co(n)?n:CM(n)}function TM(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function EM(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`?KC(e):t===`number`?qC(e):JC(e)}function DM(e){return e===`number`?0:e===`boolean`?!1:``}var OM=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];holds=new Sj;identities=new Map;lanes=X.observable.map(void 0,{deep:!1});inputs=X.observable.box(SM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=gj({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t,n=``,r,i=null){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.sessionState=r}view(t){return new e(t,new lw(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,GC(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>TM(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 YC(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=EM(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},vM(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,X.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,X.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:xM(r),refresh:n}))}hold(e,t){(0,X.runInAction)(()=>{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]}));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,ao(t,n))}}documentPublisher(e,t){let n=t===void 0?so(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(it(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(_j(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=EM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=XC(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(bM);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(bM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.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,X.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(_j(this.store)).map(e=>e.plain).join(``))}catch(e){return XC(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):so(`unread`)}},e=>n({kind:`key`,hash:oM(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`)?F(e.map(e=>e.value).join(`,`)):so(`unread`)},e=>n({kind:`key`,hash:oM(e)}));break}}onReads(e,t,n){let r,i=(0,X.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 EM(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,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function kM(e,t){let n=Jb[e],r=ex(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 AM=Object.fromEntries([...ox].map(([e,t])=>[t,kM(e,t)])),jM={subscribers:`number`,fps:`number`,shown:`boolean`},MM=Object.keys(jM),NM={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bM]:{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:``},...AM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(mb.flatMap(e=>MM.map(t=>[yb(e,t),{kind:`input`,path:yb(e,t),type:jM[t],default:vb[t]}]))),[_b(`by`)]:{kind:`input`,path:_b(`by`),default:gb.by},[_b(`fps`)]:{kind:`input`,path:_b(`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:``}},PM={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 FM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(PM,t)?t:void 0}const IM=Object.fromEntries(dv.map(e=>[e,ox.get(e)]));function LM(e){return dv.find(t=>IM[t]===e)}function RM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of bC(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 Zv(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(bM);for(let t of Object.values(e.actions)){r.add(bM);for(let[,e]of Kx(t))i(e);let e=`set`in t?sx.get(t.set):void 0,n=`persist`in t?ox.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function zM(e,t,n){let r=zC({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of RM(e,t,n.helpers)){if(RC(a,r))continue;let e=NM[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 BM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function VM(e){return e}function HM(e,t,n){return n===void 0?Yx+BM(e)+`.`+BM(t):UM(n)}function UM(e){return Yx+BM(e)}function WM(e,t){return e+`.`+t}function GM(e){return Xx+e}const KM=[`closeOnPick`,`paged`,`key`,`distribution`],qM=e=>KM.includes(e),JM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${m_.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function YM(e){for(let t of Object.keys(e))if(!qM(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&&!h_(r))throw Error(`{{ menu }} option "distribution" must be one of: ${m_.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:__(r)}}const XM=e=>`from`in e?e.from:e.themes;function ZM(e,t,n){return e===`bool`?Bv(t)!==null:`min`in e?Vv(t,e)!==null:Hx(XM(e),n).members.includes(t)}function QM(e,t){if(e===`bool`)return Rv.join(` or `);if(!(`min`in e)){let n=XM(e),{members:r}=Hx(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 $M(e){return{label:e.label,domain:eN(e.domain)}}function eN(e){return e===`theme`?{themes:Bx}:e===`bool`||`min`in e?e:{from:e}}function tN(e,t,n,r,i){let a=aa(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Rv]}},variables:{}};if(`from`in o)return nN(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 nN(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 nN(e,t,n,r,i){let a={variable:n,key:n,member:t},o=WM(n,t),s=`${t}.open`,c=GM(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]:pa(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:fa(n,ea),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const rN=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],iN=Object.fromEntries(rN.map(e=>[e.member,e.label])),aN={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},oN=Object.keys(aN),sN=cx(e=>nx[e].place),cN=e=>Object.hasOwn(aN,e),lN=(e,t)=>e===t||cN(e)&&lN(sN[aN[e].beside],t),uN=e=>cN(e)?`${uN(sN[aN[e].beside])} › ${aN[e].trigger}`:e===`door`?`first line`:iN[e],dN=e=>uN(sN[e]),fN=()=>[`door`,...rN.map(e=>e.member)].flatMap(e=>[e,...oN.filter(t=>lN(t,e))]).map(e=>({path:uN(e),names:rx.filter(t=>sN[t]===e)})).filter(({names:e})=>e.length>0),pN=e=>{let{setting:t,on:n,inTmux:r}=pb[e].switch;return`${pb[e].label} is off — turn it on in the settings menu's ${dN(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},mN=Object.fromEntries(Object.entries(Jb).map(([e,t])=>[e,t.spec]));function hN(e){return gN(Jb[e])}function gN(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function _N(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 vN(e){return _N(`${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 yN(e){return _N(`${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 bN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&fv(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 xN={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 ${dN(`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."},SN={noun:`globals key`,fields:mN,removed:xN},CN={preset:vN(`a preset`),menuGlyph:yN(`a preset`)},wN={noun:`preset globals key`,fields:{...mN,...CN},removed:xN};function TN(e){return FN(e)&&!(e in CN)}const EN=`is decided later than any rule could be settled`,DN={noun:`editGlobals key`,removed:xN,fields:{...mN,preset:vN(`the editGlobals fragment`),menuGlyph:yN(`the editGlobals fragment`),palette:bN(mN.palette,`the editGlobals fragment`,EN),style:bN(mN.style,`the editGlobals fragment`,EN),effect:bN(mN.effect,`the editGlobals fragment`,EN)}},ON={noun:`theme default key`,fields:{...Object.fromEntries(Zb.map(e=>[e,mN[e]])),style:bN(mN.style,`a theme's default`,`is the look that theme wears by name`)}};function kN(e,t){if(!Hv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${zy(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${rv(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=By(e,ON,t,i);a!==null&&(n[r]=a)}return n}function AN(e,t,n){return n===void 0?{}:By(e,SN,t,n)??{}}function jN(e,t,n){return By(e,wN,t,n)??{}}function MN(){return sb(wN)}function NN(e,t,n){return By(e,DN,t,n)??{}}const PN=new Set(Object.keys(mN));function FN(e){return PN.has(e)}function IN(e){return Object.hasOwn(xN,e)?xN[e]:void 0}function LN(){return[...PN]}const RN=new Map(Object.entries(Jb).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function zN(e){let t=new Map;for(let[n,r]of RN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const BN=/^segments\.([^.]+)\.palette$/,VN=/^presets\.(.+)\.root$/,HN=/^presets\.(.+)\.globals\.([^.]+)$/,UN=/^themeDefaults\.(.+)\.([^.]+)$/;function WN(e){return`presets.${e}.root`}function GN(e,t){return`themeDefaults.${e}.${t}`}const KN=e=>Zb.includes(e);function qN(e,t){return`presets.${e}.globals.${t}`}function JN(e){if(FN(e))return{scope:`globals`,field:e};let t=BN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=HN.exec(e);if(n&&TN(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=UN.exec(e);if(r&&KN(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=VN.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function YN(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 XN=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],ZN=[...XN,`other`],QN={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},$N=nE({fromString:e=>e});function eP(e){let t=BM(e);return $x.find(e=>t.startsWith(BM(e)))}function tP(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 nP(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=rC(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=rC(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 rP=`edit.mode`,iP=`edit.configure`,aP=`edit.toggle`,oP=`arrange`,sP=`${Zx}draft.`;function cP(e,t){return`${e}:${t}`}const lP={variable:rP,key:rP,member:oP},uP=sa(lP);function Nte(e){try{return $N.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Pte(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`&&Nte(t))return!0}return!1}function Fte(e,t){if(tP(e,t,Zx,`edit mode`),!Pte(t))return;let{variables:n,actions:r}=dP();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function dP(){return{variables:{[rP]:{...fa(rP,ea),within:[rS]},[iP]:{...fa(iP,ea),within:[lP]}},actions:{[aP]:pa(rP,oP),"edit.unconfigure":{set:iP,to:ea}}}}function fP(e,t,n,r){let i={variable:e,key:e,member:ta};return r.variables[e]={...fa(e,ea),...n.length>0&&{within:n}},r.actions[e]=pa(e,ta),r.segments[e]={template:la(e,`(?)`,`✕`),...Ite(n)},oa(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 Ite(e){let[t,...n]=e;return t===void 0?{}:{when:sa(t,...n)}}const pP=`none`;function mP(e){return wu(e,`background`)}var Lte=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Rte(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=hP(n,i),l=c!==pP,u=l?c===void 0?o:gP(a,c,`bg`):mP(a);e.bg=u;let d=hP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:N_(a,e,t))(u):void 0:gP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function hP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function gP(e,t,n){try{return wu(e,t)}catch(e){throw e instanceof Cu?new Lte(t,n,e.message):e}}const _P=`🔧`,vP={help:[`-h`,`--help`],version:[`-V`,`--version`]},yP=[...new Set(Object.values(pb).map(e=>dN(e.switch.setting)))].join(` or `),zte=Math.max(...Object.values(nx).map(e=>e.configKey.length))+2,bP=[`✚ inserts`,`✖ removes`,`${_P} configures`,`↺ resets layout`],xP={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`]},Bte=`
|
|
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
|
+
${vP.help.join(`, `).padEnd(25)}Show this help
|
|
77
|
+
${vP.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
|
|
@@ -97,21 +97,21 @@ Configuration:
|
|
|
97
97
|
the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
|
|
98
98
|
and 💾 save, which appears while you have unsaved changes and writes them to
|
|
99
99
|
your config file. Under it are its
|
|
100
|
-
tabs, ${
|
|
101
|
-
${
|
|
100
|
+
tabs, ${rN.map(e=>e.label).join(`, `)};
|
|
101
|
+
${iN.session} holds quick actions and commands, ${iN.layout} a new preset.
|
|
102
102
|
A change applies to this session at once.
|
|
103
103
|
Where each setting is in the menu: the globals field that sets it in a
|
|
104
104
|
config file, then the control's label.
|
|
105
|
-
${
|
|
105
|
+
${fN().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${nx[e].configKey.padEnd(zte)}${nx[e].label}`)]).join(`
|
|
106
106
|
`)}
|
|
107
107
|
The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
|
|
108
108
|
failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
|
|
109
109
|
|
|
110
110
|
Anywhere the bar shows (?), clicking it reveals these same instructions
|
|
111
|
-
in place. In edit mode: ${
|
|
111
|
+
in place. In edit mode: ${bP.join(`, `)}.
|
|
112
112
|
|
|
113
|
-
Animation lanes (each switched in the settings menu's ${
|
|
114
|
-
${
|
|
113
|
+
Animation lanes (each switched in the settings menu's ${yP}):
|
|
114
|
+
${mb.map(e=>` ${pb[e].label}\n${xP[e].map(e=>` ${e}`).join(`
|
|
115
115
|
`)}`).join(`
|
|
116
116
|
`)}
|
|
117
117
|
|
|
@@ -151,17 +151,17 @@ Subcommands:
|
|
|
151
151
|
Claude Code's statusline JSON from stdin (one object
|
|
152
152
|
a line) and sends it as the session's data
|
|
153
153
|
(--config rides with it). LANE is one of
|
|
154
|
-
${
|
|
154
|
+
${mb.join(`, `)}:
|
|
155
155
|
the experimental lane this stream serves,
|
|
156
156
|
which streams only while its toggle in the settings
|
|
157
|
-
menu's ${
|
|
157
|
+
menu's ${yP} is on.
|
|
158
158
|
bar-pane PANE Draw the bar of the Claude Code session in tmux
|
|
159
159
|
pane PANE (e.g. %3) in this pane, as the daemon
|
|
160
160
|
pushes it, while this pane is shown. The bar is
|
|
161
161
|
drawn at PANE's width, so split PANE with -v for a
|
|
162
162
|
pane under it that fits. Experimental:
|
|
163
|
-
runs while ${
|
|
164
|
-
menu's ${
|
|
163
|
+
runs while ${pb.pane.label} is on in the settings
|
|
164
|
+
menu's ${dN(pb.pane.switch.setting)}.
|
|
165
165
|
|
|
166
166
|
Config tooling:
|
|
167
167
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -187,27 +187,27 @@ Config tooling:
|
|
|
187
187
|
config [--json] The effective merged config. (All three query the
|
|
188
188
|
running daemon; none spawn one.)
|
|
189
189
|
|
|
190
|
-
`,
|
|
191
|
-
`)}function
|
|
192
|
-
`}const one=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function $P({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&one(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function eF(e){return e.map(e=>e.text).join(``)}const sne={};function tF(e,t){let n=Sl(t.colorSystem),{time:r}=t,i=1/0,a=[...kf(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:NP,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:sne}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:rne(a,n.colorSystem),nextChange:Math.min(G.nextChange(a),i)}}const nF=new Map;function cne(e){let t=nF.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}=Vm.plain,a=new dm({glyph:n(r.glyph),ascii:r.ascii},i);return nF.set(e,a),a}function rF(e,t){return e===`plain`&&t!==void 0?cne(t):Vm[e]}const iF=new Map;function aF(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=iF.get(t);if(n!==void 0)return n;let r=rF(e.endcaps,e.separator),i=e=>new q(`x`,{end:``,overflow:`ignore`,style:new W({bgcolor:e})}),a=e=>{let{lines:t}=tF(new Pp(e,r),{colorSystem:null});return new q(eF(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return iF.set(t,s),s}function oF(e){return aF(e).chrome}function sF(e){return aF(e).seam}const lne=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function cF(e){return[...new Set(e.match(lne)??[])].join(``)}function une(e){let t=rF(e.endcaps,e.separator),n=e=>new q(`x`,{end:``,style:new W({bgcolor:e})}),{lines:r}=tF(new Pp([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return cF(eF(r.flat()))}function lF(e){return e.wrap?e.width:1/0}function dne(e,t){return tF(new q(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(eF)}function uF(e,t,n=FP){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=rF(t.endcaps,t.separator),i=Number.isFinite(lF(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new Mg([...e],{joiner:r}):new Pp([...e],r),s=n.kind===`still`?tF(o,a):tF(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function fne(e,t){return ZP(uF(e,t).lines,t.colorCompatibility)}const pne=[`moves`,`can-move`,`still`];function dF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const mne=[`statusline`,`frames`],fF=e=>e?.kind===`frames`?`frames`:`statusline`,hne=[`carried`,`missing`,`unanswered`];function gne(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:dF(e)===`no`?`unanswered`:`missing`}function _ne(e){return{path:e.transcript_path,answered:dF(e)===`yes`}}const pF=[...pne,`failed`,`drawing`];var vne=class{seen=new Map;see(e,t,n,r){let i=fF(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 mF={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`}}},hF=e=>mF[e];function yne(e){return hF(e).glyphs.kind===`bundled`}function bne(e){return hF(e).glyphs.kind===`configured`}const gF=e=>hF(e).label,xne=[{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 Sne(e,t){let n=t.codePointAt(0);return xne.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&yF(e,t)===!0)}const _F=Object.keys(mF);function vF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function yF(e,t){let n=vF(e),r=vF(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 Cne(e){for(let t of _F){let n=hF(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 bF(e){let t=_F.find(t=>hF(t).term===e);return t===void 0?null:{name:t,version:null}}function wne(e){let t=Cne(e.termtype)??bF(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 Tne(e){let t=e.TERM_PROGRAM,n=_F.find(e=>hF(e).program===t),r=n===void 0?bF(e.TERM):{name:n,version:hF(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 xF(e){switch(e.kind){case`known`:return gF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function SF(e){switch(e.kind){case`known`:return gF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Ene({name:e,version:t}){let n=hF(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=yF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Dne=_F.filter(e=>hF(e).links!==null).map(gF).join(`, `);function CF(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(!Ho(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||!Ho(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function wF(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 One=[`managed`,`project`],kne=e=>!One.includes(e.scope),Ane={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:zo(t.projectDir)}),user:e=>({scope:`user`,path:e})},TF=[`drawn`,`boxes`],EF=1024*1024,DF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function jne(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 OF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const kF=pc.truecolor;function AF(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 Mne={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>AF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=wF(t.sources,kF);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:`${kF} 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`,kF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Ane[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 ${kF} to "1" there`}:o(s)})},Nne={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>AF(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"})},Pne={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:`${DF(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 ${DF(e.value.of)} measured`}},Fne={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},Ine={argument:`command argument`,environment:`$${OP}`,unknown:`source unknown`};function Lne({target:e,layers:t}){return e.source===`search`?t.length===0?MP(t):`${MP(t)} (searched)`:`${e.path} (${Ine[e.source]})`}function Rne(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
193
|
-
`).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}" ${Fne[e]}`)]}}const zne={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=Lne(e),n=OF(Rne(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},jF="re-run `cc-candybar install`";function Bne(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:// — ${jF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${jF}`]}function Vne(e){return e===null?[]:[`the daemon (${e.theirs}) is another build than this client (${e.mine}), so it may not read the link this build sends`]}const Hne={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 — ${jF}`};case`lost`:return OF([...Bne(e.opener),...e.unopened===null?[...Vne(e.otherBuild),`a cc-candybar:// link was opened and did not arrive at the daemon`]:[`a cc-candybar:// link could not be opened — ${e.unopened}`]])}}};function MF({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 NF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${gb.join(`|`)}>\``:e.checkout===null?jF:`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 — ${NF(e,`native`)}`];let{bundle:i,source:a}=MF(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} — ${NF(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 — ${NF(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 PF=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)`},Wne={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`:`${PF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:OF([...new Set(i.flatMap(e=>Une(n,r,e)))])}};function FF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||yi(e.identity,t.value.through)):[]}function IF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Gne={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`?IF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return OF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=FF(e.value,n),u=OF([...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 ${P(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 ${P(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Si(o.charge.bytes,s)?[`the daemon holds ${Ei(o.charge)} of its ${P(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}}}},LF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Kne(e,t){let n=xF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Ene(e.terminal):{kind:`unknown`}}function qne({identified:e,tmuxClient:t},n){let r=SF(e),i=Kne(e,n),a=xF(e)===null?LF:`${LF}, 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: ${Dne}`];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 Jne={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 OF(qne(t,n))}}},RF=e=>e.filter(e=>e.role===`statusline`),Yne={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})=>Zne(e,Xne(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:zF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:PF(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}}},Xne=e=>{let t=RF(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`}},zF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function Zne(e,t){let n=CF(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 zF(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 kne(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 BF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function Qne(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return SF(e);case`bundling`:case`unread`:case`configured`:return[gF(e.name),e.version].filter(e=>e!==null).join(` `)}}function VF(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return xF(e);case`bundling`:case`unread`:return gF(e.name);case`configured`:{let t=gF(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 HF(e){let t=VF(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${BF(e.glyphs)}`}}const UF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=HF(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=Qne(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 ${BF(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=mF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:yF(i.version,e);if(t===!0)return{ok:!0};let n=gF(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 ${BF(n)} — set a Nerd Font as its font`)}}}};function WF(e){return e.join(`, `)}function GF(e){return`or set missingData: "ignore" on ${WF(e)}`}function KF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${WF(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`?[`${WF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${GF(t)}`]:[`${WF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${GF(t)}`]}function qF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${WF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${WF(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`:`${WF(n)}: ${PF(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`)?[`${WF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${WF(n)}`]:[]}const JF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>OF([...KF(e.pullRequests),...qF(e.rateLimits,t)])};function YF({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 ${EF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const XF=[zne,Wne,Gne,Hne,Jne,Mne,Nne,Pne,Yne,UF,JF,{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`:`${PF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:OF(e.value.flatMap(YF))}],ZF=XF.filter(e=>e.takesMark);function QF(e){return XF.map(t=>({check:t,verdict:t.probe(e)}))}function $F(e){return XF.find(t=>t.name===e)}const eI=`${tS}doctor.`;function tI(e){let t=`${eI}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function nI({target:e}){return`configTarget=${e.source}`}function rI(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?xF(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 iI(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 aI(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}=MF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const oI=e=>`${e>=0?`+`:``}${P(e)}`;function sI({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${IF(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`:`${FF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Di(i.charge)}${i.charge.kind===`stand-in`?`(${oI(-i.charge.gap)})`:``}:${P(i.charge.bytes)}`}/${P(a)} postMortems=${s}`}function cI(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 lI(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>uI(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=RF(r.flatMap(e=>e.bars));return`frames=${pF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function uI(e){let t=CF(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 dI(e){let t=wF(e,kF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function fI(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 pI(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=HF(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 mI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function hI(e){return e.flatMap(({check:e,verdict:t})=>{let n=tI(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:zv},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:mI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?zv:Rv},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const gI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function _I(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(gI).map(([t,n])=>[`${e}${t}`,n]))}}const vI=`armed`,yI=`disarmed`,bI=`.armed`,xI=e=>e.endsWith(bI);function SI(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 CI(e,t,n){let r=`${e}${bI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${vI}")`,s=SI(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:vI},[a]:{set:r,to:yI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:yI}},disarm:a}}const wI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function TI(e){return typeof e==`string`&&wI.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 EI(e){let t=TI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const DI=[`/compact`,`/model`],OI=`/clear`;function kI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=CI(`${e}clear`,{arm:OI,confirm:`${OI} ✓ confirm`},[{action:n,when:`true`}]);return{template:DI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${mb} }}`,actions:{...Object.fromEntries(DI.map(e=>[t(e),{slash:EI(e)}])),...r.actions,[n]:{slash:EI(OI)}},variables:r.variables,disarm:r.disarm}}const AI=Array.from({length:10},(e,t)=>(t+1)*1e5),jI=AI[0],MI=AI[AI.length-1];function NI(e){let t=Io(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=jI&&n<=MI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${jI}–${MI} tokens)`,`parse`)}function PI(e,t){let n=Math.min(t??MI,MI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:AI.filter(e=>e<r).at(-1)??0,higher:AI.find(e=>e>r&&e<=n)??0}}function FI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${mb} }}{{ 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:EI(`/autocompact auto`)},...Object.fromEntries(AI.map(t=>[`${e}${t}`,{slash:EI(`/autocompact ${t}`)}]))}}}const II=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 }}`,LI=`${tS}edit`,RI=`${tS}toolbar`,zI=_I(tS),BI=`${tS}commands`,VI=kI(`${BI}.`),HI=`${tS}autocompact`,UI=FI(`${HI}.`,II),WI=e=>({kind:`segment`,name:e}),GI=`${tS}tab`,KI=e=>`${GI}.${e}`,qI=e=>`${KI(e)}.toggle`,JI=e=>({variable:GI,key:GI,member:e}),YI=`${tS}save`,XI=`${tS}preset.save`,ZI=`${tS}preset.delete`,QI=e=>`${tS}${e}`,$I=e=>`${tS}apply.${e}`,eL=e=>`${tS}reset.${e}`,tL=`${tS}themeDefault.save`,nL=`${tS}themeDefault.differs`,rL=`${tS}themeDefault.theme`,iL={when:`{{ .${nL} }}`,template:`{{ action "${tL}" (printf "⤓ default for %s" .${rL}) }} {{ swatch "${$I(`theme`)}" .${rL} }}`},aL=`${tS}resetAll`,oL=`${iS}.toggle`,sL=`${tS}undo`,cL=`${tS}back`,lL=`${cL}.step`,uL=`${tS}navigation.back`,dL=cL,fL={template:`{{ if gt .${uL} 0 }}{{ action "${cL}" "◁" }}{{ else }}{{ fg (${TP}) "◁" }}{{ end }}`},pL=`${tS}redo`,mL=`${tS}doctor`,hL=`${mL}.run`,gL=e=>`${mL}.fix.${e}`,_L=(e,t)=>`${mL}.mark.${e}.${t}`,vL=e=>`${mL}.${e}`,yL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},bL=KM(`${tS}pickers`),xL=e=>`${tS}${e}`,SL=e=>`${xL(e)}.toggle`,CL=e=>dN(e)?KM(`${tS}${e}Pickers`):bL,wL=e=>{let t=CL(uN[cN[e].beside]);return{variable:t,key:t,member:e}},TL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${ZI}" (printf "🚮 delete %s" .${ax.preset.effectiveVar}) }}`}},EL=(e,t)=>`${tS}list.${e}.${t}`,DL=e=>`${tS}resettable.${e}`,OL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${DL(e.name)})`).join(` `)})`,kL=gb.map(e=>[hb[e].switch.setting,e]),AL={variables:{},actions:{},segments:{}},jL=Object.fromEntries(kL.map(([e,t])=>[e,hP(`${tS}help.${e}`,wP[t],[],AL)])),ML=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],NL=e=>{let t=t=>`.${xb(e,t)}`,n=ML.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${ax[hb[e].switch.setting].effectiveVar} ${JSON.stringify(hb[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},PL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${sS}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,FL=`${tS}fps`,IL=`{{ if eq .${yb(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${yb(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,LL=Object.fromEntries(kL.map(([e,t])=>[e,NL(t)])),RL=e=>lN.filter(t=>cN[t].beside===e),zL=Object.keys(ax).map(e=>{let t=ax[e],n=uN[e];return{...t,name:e,place:n,control:iN({label:t.label,domain:vN(t.configKey)},t.sessionKey,t.effectiveVar,$I(e),CL(n)),beneath:t.previews.map(e=>TL[e]),help:[jL[e]].filter(e=>e!==void 0),submenus:RL(e)}}),BL=e=>zL.filter(t=>t.place===e),VL=e=>zL.filter(t=>fN(t.place,e)),HL=e=>t=>`(print ${da(t)} (ternary ${da(` •`)} "" ${OL(VL(e))}))`,UL=e=>BL(e).flatMap(e=>[tR(e),...e.help,...e.submenus.map(e=>oa(xL(e),wL(e),cR(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(zL.flatMap(e=>[e.sessionKey,e.configKey]));const WL=CI(aL,{arm:`⟲`,confirm:`⟲ reset all?`},zL.map(e=>({action:eL(e.name),when:e.shown}))),GL=[`unsaved`,`history.undo`,`history.redo`],KL=e=>`${tS}${e}`,qL=KL(`unsaved`),JL=(e,t)=>({body:t,shown:`(gt .${KL(e)} 0)`}),YL=[JL(`unsaved`,`{{ action "${YI}" (printf "💾 save %d" .${qL}) }}`),JL(`history.undo`,`{{ action "${sL}" "↶" }}`),JL(`history.redo`,`{{ action "${pL}" "↷" }}`),{body:WL.template,shown:`(or ${OL(zL)} ${WL.armed})`}],XL={when:`{{ or ${YL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+YL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},ZL=[{step:WL,place:`door`},{step:VI,place:`session`}],QL=e=>e.map(e=>e.step.disarm),$L=QL(ZL),eR=QL(ZL.filter(e=>e.place!==`door`));function tR(e){let t=QI(e.name);return e.control.kind===`inline`?WI(t):oa(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>WI(EL(e.name,n)))},`drop`)}function nR(e){return e===iS}function rR(e){let t=WI(iS);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[rR(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 iR(e){return aR(e)>0?e:rR(e)}function aR(e){let t=0;for(let n of $v(e))n.kind===`segment`&&nR(n.name)&&(t+=1);return t}function oR(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&nR(e.name)||e.opens!==void 0&&oR(e.opens.body,!0):e.children.some(e=>oR(e,n))}const sR={door:{direction:`horizontal`,content:[WI(dL)],after:[WI(LI),WI(YI)]},session:{direction:`vertical`,content:[WI(RI),{kind:`container`,direction:`horizontal`,children:[WI(BI),WI(HI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[WI(XI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[WI(mL),...XF.map(e=>WI(vL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[WI(tL)]},toggles:{direction:`horizontal`,content:[],after:[]}};function cR(e){let{direction:t,content:n,after:r}=sR[e];return{kind:`container`,direction:t,children:[...n,...UL(e),...r]}}function lR(e){return e.kind===`segment`?nR(e.name)?{kind:`container`,direction:`horizontal`,children:[oa(e.name,oS,dR,`above`),WI(FL)]}:e:fR(e)}function uR(){return{kind:`container`,direction:`vertical`,children:[cR(`door`),{kind:`container`,direction:`horizontal`,children:oN.map(({member:e})=>oa(KI(e),JI(e),cR(e),`drop`))}]}}const dR=uR();function fR(e){return{...e,children:e.children.map(e=>lR(e))}}function pR(e){let t={variables:{[iS]:fa(iS,ea),[sS]:{kind:`state`,key:sS,default:`0`}},actions:{[oL]:pa(iS,aS),[sS]:{set:sS,int:!0},[iS]:{do:[oL,...$L]},[hL]:{doctor:`run`},...zI.actions,...VI.actions,...UI.actions,[YI]:{save:!0},[sL]:{undo:!0},[lL]:{back:!0},[cL]:{do:[lL,...$L]},[pL]:{redo:!0},[XI]:{preset:`save`},[tL]:{themeDefault:`save`},[ZI]:{preset:`delete`,name:`{{ .${ax.preset.effectiveVar} }}`}},segments:{[iS]:{template:`{{ $door := ${ua(iS,da(e),da(`✖`))} }}{{ if ${ca(oS)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+PL},[FL]:{template:IL},[RI]:{template:zI.template},[BI]:{template:VI.template,when:VI.when},[HI]:{template:UI.template,bg:UI.bg,when:UI.when},[dL]:fL,[YI]:XL,[tL]:iL,[XI]:{template:`{{ action "${XI}" "+ preset" }}`},[mL]:{template:`{{ action "${hL}" "🩺 doctor" }}`},[LI]:{template:`{{ action "${cP}" "✎ arrange" "✎ done" }}`}}};t.variables[nL]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[rL]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[uL]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of GL)t.variables[KL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[GI]=fa(GI,ea);for(let{member:e,label:n}of oN){t.actions[qI(e)]=pa(GI,e),t.actions[KI(e)]={do:[qI(e),...eR]};let r=HL(e);t.segments[KI(e)]={template:`{{ ${ua(KI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,VI.variables,WL.variables),hR(t),mR(t),t}function mR(e){for(let t of XF){let n=tI(t.name),r=gL(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?TF:[];for(let n of i)e.actions[_L(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${_L(t.name,e)}" "${yL[e]}" }}`).join(``);e.segments[vL(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} "${Rv}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function hR(e){for(let t of zL){Object.assign(e.actions,t.control.actions);let n=eL(t.name);e.actions[n]={reset:t.configKey},e.variables[DL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${DL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[QI(t.name)]={template:`${t.control.template}${LL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[EL(t.name,r)]=n})}Object.assign(e.actions,WL.actions),Object.assign(e.variables,AL.variables),Object.assign(e.actions,AL.actions),Object.assign(e.segments,AL.segments);for(let t of lN){let n=wL(t);e.actions[SL(t)]=pa(n.key,n.member),e.segments[xL(t)]={template:`{{ action "${SL(t)}" ${HL(t)(cN[t].trigger)} }}`}}}function gR(e){let{variables:t,actions:n}=mP();Object.assign(e.variables,t),Object.assign(e.actions,n)}function _R(e){let t=pR(e.globals.menuGlyph??`🍫`);gR(t);let n={...e.presets},r=[];for(let t of Fx(e.presets)){let{node:i}=Rx(e,t),a=lR(iR(i));r.push(a),n[t]={...Lx(e.presets,t),root:a}}let i=HM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const vR=`${eS}live`,yR=[`☐ live`,`☑ live`],bR=`${eS}done`,xR=`${eS}cancel`,SR=`${eS}rewind`,CR=`${eS}changes`,wR=`(gt .${CR} 0)`,TR=`(or ${wR} (gt .${qL} 0))`,ER={variable:vR,key:vR,member:ta};function DR(e){return`${eS}configuring.p${e}`}function OR(e){return`and ${ca(fP)} (not ${ca(ER)}) (ne .${DR(e)} "true")`}function kR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${sP} "${aa(e)}")`).join(` `)} false }}`}}function AR(e,t,n){return`{{ if ${OR(e)} }}${t}{{ else }}${n}{{ end }}`}const jR=`{{ and ${ca(fP)} .preset.customized }}`,MR=rS;function NR(e){return new Map([...Ete(e),...FR(e)])}const PR=`${eS}addable`;function FR(e){return new Map([[PR,{members:Object.keys(e.segments).filter(e=>!MR(e)),library:{groups:eP.map(e=>({id:e,label:tP[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function IR(e,t,n){return n.segments[e]={template:t,when:pP,bg:gP},{kind:`segment`,name:e}}function LR(e,t,n){let r=`${eS}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${P_}`}) (action "${r}" "✖") }}`}function RR(e){return`{{ if ${ca(fP)} }}${e}{{ end }}`}function zR(e,t){return e.reduce((e,t)=>`{{ if and ${ca(fP)} ${ca(t)} }}true{{ else }}${e}{{ end }}`,t)}function BR(e){return e.flatMap(e=>[...$v(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function VR(e,t,n){return`${uP}${e}.${t}.${n}`}function HR(e,t,n,r){let i=Yv(n),a=`${eS}${e.presetIdent}`,o=dP(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=KM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:ea},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:sP,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=VR(e.presetIdent,i,r),l=`${uP}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:yy(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=iN(nN(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 oa(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${bP}" }}`,ref:{variable:sP,key:sP,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const UR=`${eS}label:`;function WR(e){if(e.startsWith(UR)){let t=e.slice(UR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function GR(e,t,n,r){let i=Yv(e),a=KR(n,i,e,t,i),o=Object.fromEntries(my.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...oa(a,r.ref,r.body,`drop`,zR([r.ref],`{{ ${OR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(my.map(e=>[e,r.drafts[e]]))}}function KR(e,t,n,r,i){let a=`${UR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${aa(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function qR(e,t,n,r){let i=Yv(e),a=n?[XR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=XR(r,o,i,`after`),c=LR(r,o,i),l=r.segments[e.name],u=HR(r,o,e,hy(l)),d=RR(c),f=RR(u.term);return[...a.map(e=>IR(e.host,e.template,r.artifacts)),{...GR(e,l,r,u),lead:d,trail:f},{...t,when:AR(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},IR(s.host,s.template,r.artifacts)]}function JR(e){return s.join(s.basename(s.dirname(e)),s.basename(e))}function YR(e,t,n,r){let i=r.segments[e.name],a=Yv(e);return[{kind:`segment`,name:KR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${JR(t.file)} ${t.entry}`),when:`{{ ${OR(r.presetIdent)} }}`},{...n,when:AR(r.presetIdent,`false`,e.when??`true`)}]}function XR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${eS}${i}.insert.${t}`,s=`${eS}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:PR,anchor:n,relation:r};let c=WM(o),l=GM(s,o,void 0),u=JM(l),d=qM(l,c);return a.variables[l]={...fa(l,ea),within:[fP]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=pa(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ca({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${P_}`}) $m }}{{ end }}`}}function ZR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!MR(e.name)&&e.insertedBy===void 0),i=e=>ZR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Qv(o,i);if(MR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?qR(o,s,a===r,t):YR(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:zR(BR(n),AR(t.presetIdent,`true`,e.when))}}}function QR(e,t,n,r,i,a,o){let s=`${eS}${t}.resetLayout`,c=`${eS}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:jR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},$R(e,o)]}}function $R(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),$R(n,t)]}:{...e,children:[...e.children,t]}}function ez(e,t,n,r,i,a){let{node:o}=Rx(e,t),s={presetIdent:UM(t),rootKey:qN(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=ZR(o,s);return n.variables[DR(s.presetIdent)]=kR(s.configured),QR(c,s.presetIdent,s.rootKey,n,r,i,a)}function tz(e){let t={variables:{},actions:{},segments:{}},n=hP(`${eS}help`,CP,[fP],t);t.variables[vR]=fa(vR,ea),t.actions[vR]=pa(vR,ER.member),t.segments[vR]={template:la(vR,...yR),when:pP};let r={kind:`segment`,name:vR},i=n;t.variables[CR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[bR]={do:[YI,cP]},t.segments[bR]={template:`{{ if ${TR} }}{{ action "${bR}" "✓ save" }}{{ else }}{{ action "${bR}" "✓ done" }}{{ end }}`,when:pP},t.actions[SR]={rewind:!0},t.actions[xR]={do:[SR,cP]},t.segments[xR]={template:`{{ action "${xR}" "↩ cancel" }}`,when:`{{ and ${ca(fP)} ${wR} }}`};let a=[{kind:`segment`,name:bR},{kind:`segment`,name:xR}],o={...e.presets},s=[];for(let n of Fx(e.presets)){let c=ez(e,n,t,a,r,i);s.push(c),o[n]={...Lx(e.presets,n),root:c}}let c=HM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function nz(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function rz(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 iz(e,t,n){let r=Zv(e,new Set(n.map(Xv).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const az=/^-?\d+$/;function oz(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 sz(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!az.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 cz(e,t,n){return r=>r?az.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 lz(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=>!az.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 uz(e){return e===`config`?`set-config`:`set-state`}function dz(e,t,n){return t.kind===`int`?sz(`menu page "${e}"`):t.kind===`range`?cz(t.min,t.max,`${n} stepper "${e}"`):oz(t.allowed,`${n} "${e}"`,uz(n))}function fz(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:lz(e,n,t)}))}function pz(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 fz(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,dz(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 mz(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};pz(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=pz(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function hz(){return mz({},`config`,yz)}function gz(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:Gx(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:[nz({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[nz({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Gx(e.insertSegmentFrom,t).members.map(t=>nz({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function _z(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?ZN(n.persist):null;e?.scope===`preset-root`&&t.add(qN(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function vz(e){let t=NR(e);return[..._z(e),...Object.values(e.actions).flatMap(e=>gz(e,t))]}function yz(e){return fz(vz(e),`config`)}const bz=cv(),xz=new Set(bz),Sz=new Set(Av),Cz=e=>e?xz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${bz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},wz=e=>e?Sz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Av.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},Tz=new Set([`1`,`true`]),Ez=new Set([`0`,`false`]),Dz={endcaps:wz,theme:Cz,"toolbar-expanded":e=>Tz.has(e)?{ok:!0,value:`1`}:Ez.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function Oz(){return mz(Dz,`state`,Mz)}function kz(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:Gx(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 Az(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(Dz,e.key))}function jz(e){let t=NR(e);return Az(Object.values(e.actions).flatMap(e=>kz(e,t)))}function Mz(e){return fz(jz(e))}function Nz(e){let t=Oz(),n=hz();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 Pz=`update.dismissed`,Fz=`updateNotice`,Iz=ax.updateNotice.sessionKey;function Lz(){return Nz({config:[{key:Fz,allowed:[`false`]}],state:[{key:Iz,allowed:[`false`]},{key:Pz,allowed:[]}]})}function Rz(e){try{return h.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function zz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:Hz(t.segments,Bz(t.segments,e.segments??{})),root:Ox(e.root??Sx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:Hz(t.presets,Vz(t.presets,e.presets??{})),themeDefaults:Hz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Bz(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 Vz(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 Hz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Uz=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 Wz(e){let t=Uz.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 Gz(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: ${ay.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Jz(e,`${t}.cache`,n.cache)}function Kz(e){return{required:!0,json:Yz(),parse:(t,n,r,i)=>Gz(t,n,i,e)??void 0}}const qz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Zz(n)?{ttl:n}:qy(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Y(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return qy(e,t,`cache.watch_file must be a path string, got ${Y(n)}`);let r=ab(`cache.watch_file`,n);return r===null?{watch_file:n}:qy(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}:qy(e,t,`cache.depends_on must be an array of variable-name strings, got ${Y(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:qy(e,t,`cache.key must be a non-empty template string, got ${Y(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:qy(e,t,`cache.never must be the literal boolean true, got ${Y(n)}`)}}};function Jz(e,t,n){return Jy(e,qz,t,n)}function Yz(){return fb(qz)}const Xz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Zz(e){return Xz.test(e)}const Qz=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 $z(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 eB(e){let t=Qz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${$z(t)}`}function tB(e){let t=Qz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${$z(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const nB=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`]]),rB=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 iB(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 aB(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`?rB.get(e.field):void 0;if(n===void 0){let e=[...rB.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 ${iB(n.declare)} under a name of your own`}const oB=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 sB(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`?oB.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 ${iB(n.declare)} under a name of your own`}function cB(e,t,n){if(n===void 0)return{};if(!Wv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Vy(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Yy(e,AB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function lB(){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 ${Vy(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function uB(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Ly(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const dB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:qy(e,t,`parse.text must be the literal boolean true, got ${Y(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?fB(e,t,n):qy(e,t,`parse.regex must be a pattern string, got ${Y(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:qy(e,t,`parse.json must be the literal boolean true, got ${Y(n)}`)}}};function fB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return qy(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:qy(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function pB(){return{required:!1,json:fb(dB),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:Jy(e,dB,`${t}.parse`,r.parse)??void 0)}}function mB(){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)=>Wv(r.parse)&&`json`in r.parse?hB(e,t,r.default):Ry(e,t,r,`default`)}}function hB(e,t,n){if(n!==void 0)return gB(n)?n:qy(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Y(n)}`)??void 0}function gB(e){return e!==null&&KC(e)}const _B={value:lB(),default:$y()};function vB(){let e=ib();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:nB.get(a);return o===void 0?a:qy(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const yB={path:vB(),type:sb([`string`,`number`,`boolean`]),default:uB()},bB={path:ob(),readMode:sb([`whole`,`first-line`]),parse:pB(),cache:Kz(`file`),default:mB()},xB={command:ib(),parse:pB(),cache:Kz(`shell`),default:mB()};function SB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const CB={template:ib(),type:sb([`string`,`number`,`boolean`]),default:uB()},wB=SB(`a template variable recomputes whenever a variable it reads changes`),TB={layout:ib(),default:$y()},EB=SB(`a time variable reads the instant its render is drawn at`),DB={key:ib(),default:$y()},OB=`kind`;function kB(e,t,n={}){return{...Xy(OB,e,t),parse:(r,i,a)=>{Uy(r,n,i,a);let o=Wy(r,t,i,a);return o===null?null:{kind:e,...o}}}}const AB={tag:OB,noun:`source kind`,memberNoun:`variable`,arms:{literal:kB(`literal`,_B),input:kB(`input`,yB),file:kB(`file`,bB),shell:kB(`shell`,xB),template:kB(`template`,CB,wB),time:kB(`time`,TB,EB),state:kB(`state`,DB)},retired:{git:aB,env:sB}};function jB(){return db(AB)}function MB(){return{type:`object`,additionalProperties:jB()}}const NB=/^[A-Za-z_][A-Za-z0-9_]*$/,PB={pattern:NB.source},FB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},IB={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`,...PB}}}]},default:FB}},LB=[`label`,`domain`,`default`],RB=[`min`,`max`,`step`,`atLeast`];function zB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function BB(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 zB(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 zB(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?zB(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(Wv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!RB.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}}:zB(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 zB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Y(n)}`)}function VB(e,t,n){if(!Wv(n))return zB(e,t,`${t} must be { label, domain, default }, got ${Vy(n)}`);for(let r of Object.keys(n))LB.includes(r)||zB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${LB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||zB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Y(r)}`);let a=BB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!HB(n.default)||!vy(o,n.default)?zB(e,`${t}.default`,`default must be ${Sy(o)}, got ${Y(n.default)}`):o}function HB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const UB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${fy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function WB(e){return my.includes(e)}function GB(){return{required:!1,json:{type:`object`,propertyNames:{...PB,not:{enum:[...my]}},additionalProperties:IB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Wv(i))return zB(e,a,`${a} must be an object of name → { label, domain, default }, got ${Vy(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!NB.test(t)){zB(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(WB(t)){zB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${UB[t]}`);continue}let r=VB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const KB=nS.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function qB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${KB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!rS(i)?i:zB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${nS.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Y(i)}`)}}}function JB(){return{required:!1,json:{type:`object`,propertyNames:PB,additionalProperties:FB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Wv(i))return zB(e,a,`a placement's "settings" must be an object of setting name → value, got ${Vy(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))HB(n)?o[t]=n:zB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Vy(n)}`);return o}}}function YB(e){return new Set(Object.keys(e.segments).filter(e=>!rS(e)))}function XB(e,t,n){if(t===void 0)return{};if(!Wv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Vy(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Hy(e,n.has(i)?oV:aV,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function ZB(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 ${Vy(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 ${Vy(i)}`,line:J(e.source,[...t.split(`.`),n])})}const QB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function $B(){return{required:!0,json:QB,parse:(e,t,n,r)=>r[n]===void 0?qy(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${Wz(t.slice(9))}`)??void 0:ZB(e,t,n,r)}}function eV(){return{required:!1,json:QB,parse:(e,t,n,r)=>r[n]===void 0?void 0:ZB(e,t,n,r)}}function tV(){return{required:!1,json:{type:`object`,additionalProperties:QB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Wv(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${Vy(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=ZB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function nV(){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 ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function rV(){return{required:!1,json:MB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return cB(e,`${t}.${n}`,i)}}}const iV={template:$B(),description:$y(),group:sb($N),width:nV(),justify:sb(Cy),truncate:sb(wy),bg:$y(),fg:$y(),when:$y(),palette:rb(),vars:rV(),settings:GB(),missingData:sb(ly),partials:tV()},aV={noun:`segment key`,fields:iV},oV={noun:`segment key`,fields:{...iV,template:eV()}};function sV(e,t){if(t===void 0)return{};if(!Wv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Vy(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 ${Y(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function cV(e,t,n){if(t===void 0)return{};if(!Wv(t))return Z(e,`actions`,`actions must be an object, got ${Vy(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=lV(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function lV(e,t,n,r){if(!Wv(n))return Z(e,t,`${t} must be an action object, got ${Vy(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=qx.filter(e=>e in n);return i.length===1?dV(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${qx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function uV(e){return e===`<default>`?{dir:null}:s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const dV=e=>({set:(e,t,n)=>qV(e,t,n,`set`,UV),persist:(e,t,n)=>qV(e,t,n,`persist`,WV),copy:fV(`copy`),open:fV(`open`),reset:pV,undo:hV(`undo`),redo:hV(`redo`),back:hV(`back`),rewind:hV(`rewind`),save:hV(`save`),preset:gV,themeDefault:_V,doctor:yV,slash:bV,run:CV(e),do:wV});function fV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Iy(t,n,r,e);return i===null?null:{[e]:i}}}function pV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=TV(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 mV={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 hV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${mV[e]}), got ${Y(r[e])}`),null)}}function gV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${Y(r)}`),null;if(r===`save`)return{preset:`save`};let a=Iy(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function _V(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Y(n.themeDefault)}`),null)}const vV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function yV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(vV,r),a=i?vV[r]:[...new Set(Object.values(vV).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(vV).map(e=>`"${e}"`).join(`, `)}, got ${Y(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?ZF:XF;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Y(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return TF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${TF.map(e=>`"${e}"`).join(` or `)}, got ${Y(c)}`),null)}function bV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=TI(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const xV=[`run`,`env`,`refreshes`],SV=/^[A-Za-z_][A-Za-z0-9_]*$/;function CV(e){return(t,n,r)=>{for(let e of Object.keys(r))xV.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${xV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${Y(a)}`);let o=r.env??{};(!Wv(o)||Object.entries(o).some(([e,t])=>!SV.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${Y(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${Y(s)}`),`dir`in e||Z(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}}}SV.source;function wV(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${Y(r)}`),null):{do:r}}function TV(e,t,n,r,i,a){let o=Iy(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const EV={set:`the SessionState key to write`,persist:`the config globals field to write`};function DV(e,t,n,r){let i=EV[r],a=TV(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 OV(e){return e===`set`?`set-state`:`set-config`}const kV={to:JV(`set`)},AV={to:JV(`persist`)},jV={from:YV(`set`)},MV={from:YV(`persist`)},NV={min:eH(),max:eH(),by:eH()},PV={int:ZV()},FV={cycle:XV(`set`)},IV={cycle:XV(`persist`)},LV={removeSegment:QV(`removeSegment`)},RV={insertSegment:QV(`insertSegment`),anchor:QV(`anchor`),relation:$V()},zV={insertSegmentFrom:YV(`persist`),anchor:QV(`anchor`),relation:$V()},BV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},VV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function HV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Wy(e,t,n,r),c=cb(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?Qy(s,...n):s}}const UV=[HV(`set`,kV),HV(`set`,jV),HV(`set`,NV,[BV,VV]),HV(`set`,PV),HV(`set`,FV)],WV=[HV(`persist`,AV),HV(`persist`,MV),HV(`persist`,NV,[BV,VV]),HV(`persist`,IV),HV(`persist`,LV),HV(`persist`,RV,[],[`insertSegment`]),HV(`persist`,zV,[],[`insertSegmentFrom`])];function GV(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 KV(e){let t=GV(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 qV(e,t,n,r,i){let a=DV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${KV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function JV(e){let t=OV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>TV(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 YV(e){let t=OV(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Y(o)}`)}}}function XV(e){let t=OV(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Vy(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function ZV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Y(r[n])}`);return}return!0}}}function QV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Iy(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function $V(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${Y(i)}`);return}return i}}}function eH(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${Y(i)}`);return}return i}}}function tH(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const nH=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),rH=`plugin.json5`,iH=/^[a-z][a-z0-9_]*$/;function aH(e,t){let n=s.basename(s.dirname(e));return iH.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function oH(e){return`${e}.data`}function sH(e){return`${e}.json`}function cH(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:lH(e)}}}function lH(e){return e instanceof Ty?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 uH(e,t,n,r){return e.map(e=>aH(EP(s.dirname(t),e,r),n))}function dH(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:rC(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(s.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${rH}, and the folder's name is the plugin's: move this file to <dir>/<name>/${rH} and list that`;return c(t,o===void 0?e.config:pH(fH(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${s.basename(s.dirname(a))}" is not a plugin name (one matching ${iH}: 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=fH(e.config,o),d=cH(()=>{let i=h.readFileSync(a,`utf-8`),s=zz(yH(a,n,{source:i,json:ya.default.parse(i)},t),u);return PH(a,o,s),r(s,o,u!==e.config),s});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,pH(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function fH(e,t){let n=iC(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 pH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:tH(n),definition:n.path}}}}function mH(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})=>iC(t)(e))}function hH(e,t){let n=mH(e.config),r=[...e.rendering.keys()].map(iC),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=oC(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:tH(e)})):[{definition:a.definition,notice:a.notice}]}}function gH(e,t,n){let r=Fx(e.presets).flatMap(t=>[...$v(Rx(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,_H(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=mH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...CH.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=>DC(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 _H(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,vH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function vH(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 yH(e,t,{source:n,json:r},{checkout:i,home:a}){let o=rC(t),c=[],l=()=>{throw new Ty(e,c)};if(!Wv(r))return c.push({path:``,message:`a plugin definition must be an object, got ${Vy(r)}`}),l();for(let t of Object.keys(r))nH.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${s.basename(s.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...nH].join(`, `)}`});let u=r.data===void 0?void 0:LH(r.data,e,i,a,c),d=r.sources===void 0?{}:NH(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(cv()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:cB(f,`data`,{[oH(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=cB(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 (.${oH(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 g={variables:{...p,...EH(o,d),...EH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,OH(o,t)])))},segments:EH(o,kH(o,XB(f,r.segments,new Set))),helpers:EH(o,sV(f,r.helpers)),actions:EH(o,AH(o,cV(f,r.actions,{dir:h.realpathSync(s.dirname(e))})))};c.push(...wH(g,t));let _=bH(o,g);for(let[e,t]of TH(_))try{nP.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),_}function bH(e,t){let n=t=>LC(t,aC,e),r=t=>iC(`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=>xH(sy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(CH.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=>xH(sy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>SH(Xx(e,n),r))}}function xH(e,t){return oy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function SH(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 CH=[`template`,`bg`,`fg`,`when`];function wH(e,t){let n=e.helpers??{},r=nC.filter(e=>e!==t.scope).map(e=>({scope:e,ns:rC({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>iC(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 ${rC(t)}: a plugin names itself without its scope — write ${s}${aC}${n.slice(o.ns.length)}`})},o=[...[...TH(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 CC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of DC(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??{}))SH(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(oy(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*TH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of cy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of CH){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 cy(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 Yx(n))yield[`actions.${t}.${e}`,r]}function EH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function DH(e,t){return`${e}.${t}`}function OH(e,t){return t.kind===`state`?{...t,key:DH(e,t.key)}:t}function kH(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,OH(e,n)]))}]))}function AH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:DH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>DH(e,t))}:n]))}const jH=iH,MH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function NH(e,t,n){if(!Wv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${Vy(e)}`}),{};let r=s.join(h.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(MH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!jH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${jH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=IH(o,MH,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 PH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=FH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=iC(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 Ty(e,a)}function FH(e){return s.join(e.storage,sH(`<session id>`))}function IH(e,t,n){return!Wv(t)||!Wv(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)?IH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function LH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return EP(s.dirname(t),e,r);if(Wv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){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 s.resolve(n.root,t)}if(Wv(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 RH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),zH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:s.join(t,BH),scope:`repo`}]]}function zH(e){return s.join(e.dataHome,`cc-candybar`,`plugins`)}const BH=s.join(`.cc-candybar`,`plugins`);function VH(e,t){let n=RH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=HH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=aH(s.join(e,i,rH),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:s.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${rH}: move this file to ${s.join(e,`<name>`,rH)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function HH(e){try{let t=h.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()||UH(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 UH(e,t){if(!t.isSymbolicLink())return!1;try{return h.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}const WH=[`approved`,`declined`];function GH(e){return e.link.kind===`linked`?e.link.main:e.dir}const KH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function qH(e,t){let n=GH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=KH(e.value,n),i=KH(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 JH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...qH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&qH(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 YH(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 XH(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(!WH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${WH.join(` or `)}`};return{kind:`ok`,value:e}}function ZH(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 QH(e){let t=ZH(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 $H=[`json5`,`json`];function eU(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?$H.map(e=>s.join(t,`${tU}.${e}`)):[],...$H.map(e=>s.join(i,`${tU}.${e}`)),...$H.map(t=>`${nU(e)}.${t}`)])]}const tU=`.cc-candybar`;function nU(e){return s.join(e.configDir,`config`)}function rU(e){return{path:e,scope:`plugins`}}function iU(e,t,n,r,i){let a=[],o=new Map;for(let t of eU(e,n,r,i)){let n=Rz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=h.realpathSync.native(s.dirname(t)),c=s.join(r,s.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||aU(e,t)?null:{dir:r,link:dc(r)}})}let c=[...o.values()],l=JH(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),oU(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:sU(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 aU(e,t){return $H.some(n=>t===`${nU(e)}.${n}`)}function oU(e){if(e===void 0||Rz(e)!==`present`)return null;let t=HH(s.join(e,BH)),n=h.realpathSync.native(e);return{dir:n,link:dc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function sU(e,t){return t.find(t=>aU(e,t.path))?.path??`${nU(e)}.${$H[0]}`}function cU(e,t,n,r,i){let a=iU(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 lU(e){return uU(e).join(`
|
|
194
|
-
`)||null}function uU(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 dU(e,t,n){let r=eU(e,t,n).filter(e=>Rz(e)===`present`),i=new Map;for(let e of r){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),r=s.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 fU(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=h.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&&dr(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const pU={level:`error`,glyph:`⚠`,colors:VP},mU={level:`warning`,glyph:`⚠`,colors:HP},hU={level:`warning`,glyph:`⬆`,colors:HP},gU={level:`warning`,glyph:`🔒`,colors:HP},_U={level:`warning`,glyph:`🧪`,colors:HP};function vU(e,t){return{text:WP(e),link:t}}function yU(e,t,n,r,i,a){let o=new Set,s=(e,t)=>{let n=bU(e,t);for(let e of n)o.add(e);return n},c=[...r.flatMap(e=>s(e,pU)),...i,...a.flatMap(e=>s(e,mU))],l=xU(c);return c.map((r,i)=>o.has(r)?{...r,lines:[[vU(r.lines[0][0].text,SU(e,t,n,l[i],i+1))],...r.lines.slice(1)]}:r)}function bU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>vU(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 xU(e){return EU(e).map(e=>String(e*wU+1))}function SU(e,t,n,r,i){return GS(e,[{verb:PS,args:[t,n,r]}],`copy diagnostic ${i}`)}function CU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const wU=4096;function TU(e){let t=ce(`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 EU(e){let t=new Map;return e.map(e=>{let n=TU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function DU(e,t,n){return String(EU(e)[t]*wU+n+1)}const OU={error:VP,warning:HP};function kU(e){let t=CU(e),n=e.length,r=OU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:DU(e,0,0)}}function AU(e,t){let n=Number(e)-1,r=EU(t).indexOf(Math.floor(n/wU));return e===null||r===-1?null:{index:r+1,page:n%wU}}function jU(e,t){return Math.min(20,e??20,...t)}function MU(e,t,n,r,i,a){let{index:o}=t,s=e[o-1],c=FU(a),l=RU(s,c,[]),u=new W({bgcolor:s.severity.colors.bg,color:s.severity.colors.fg}),d=(e,t)=>IU(e,t===null?u:u.withLink(t)),f=(t,i)=>i===null?d(` `,null):d(t,PU(n,r,DU(e,i.index-1,i.page),`show diagnostic ${i.index} of ${e.length} page ${i.page+1}`)),p=(t,a)=>{let s=a>0?{index:o,page:a-1}:o>1?{index:o-1,page:0}:null,l=a<t-1?{index:o,page:a+1}:o<e.length?{index:o+1,page:0}:null,u=e.length>1||t>1,p=t>1?`[${o}/${e.length} ${a+1}/${t}]`:`[${o}/${e.length}]`;return LU([d(`✕`,PU(n,r,`0`)),...u?[f(`‹`,s)]:[],d(p,null),...u?[f(`›`,l)]:[],d(`⧉ copy`,SU(n,r,i,DU(e,o-1,0),o))],c)},m=1;for(;;){let e=Math.max(1,a.rows-m),n=Math.min(wU,Math.ceil(l.length/e)),r=Math.min(t.page,n-1),i=p(n,r);if(i.length>m){m=i.length;continue}let o=l.slice(r*e,(r+1)*e),s=l.length-(r+1)*e,u=r===n-1&&s>0?[...o.slice(0,-1),...LU([d(`… ${s+1} more rows: ⧉ copy has them all`,null)],{...c,wrap:!1})]:o;return[...i,...u]}}function NU(e,t,n,r,i){let{label:a,fg:o,bg:s,open:c}=kU(t),l=a===``?[]:[IU(a,new W({bgcolor:s,color:o}).withLink(PU(n,r,c)))];return RU(e,FU(i),l)}function PU(e,t,n,r){return GS(e,[{verb:uS,args:[t,sS,n]}],r)}function FU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const IU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),LU=(e,t)=>uF(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function RU(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=Kc(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=IU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Zc(e,a)).map(t=>IU(t,i(e.link)))),u=s===0?n:[];return LU([c,...l,...u],t)})}const zU=`repo-configs.json`;function BU(e){return s.join(e,`repo-configs`)}function VU(e){return s.join(BU(e),zU)}const HU=e=>{let t=fU(BU(e),zU,{},XH),n=fU(e,zU,{},XH),r=()=>h.existsSync(VU(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 UU(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:Rz(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&GH({dir:e,link:dc(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]:[])},YH(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function WU(e,t,n){return{sessionId:e,action:NS,declaration:t,evaluated:n}}function GU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=WH.map(r=>vU(`[${r===`approved`?`approve`:`decline`}]`,GS(n.to,[{verb:NS,args:[t,e,r,n.signer.sign(WU(t,e,r))]}]))),a=[vU(r,null),...i];return{severity:gU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function KU(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const qU={kind:`hidden`},JU={kind:`shown`};function YU(e,t){try{return KU(e,t)?JU:qU}catch(e){let t=$C(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function XU(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function ZU(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function QU({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function $U({text:e,placement:t,lead:n,trail:r}){return{text:eW(e),placement:t,...n!==void 0&&{lead:eW(n)},...r!==void 0&&{trail:eW(r)}}}function eW(e){let t=e.blankCopy(e.plain);t.style=PP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(PP(i).clearMetaAndLinks(),n,r);return t}function tW(e){let t=QU(e);if(t.length===1)return e.text;let n=XU(t);return n.style=e.text.style,n}function nW(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=XU(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:XU([d,...c],a)},...l.length>0&&{trail:XU([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(ZU(u,n,p),[{text:u,...f}])}function rW(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return dne(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 iW(e,t){if(e.length===0)return 0;let{lines:n}=uF(e.map(({owner:e})=>e),t),r=B(eF(n[n.length-1]));return Math.max(0,r-oF(t)+sF(t))}function aW(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=uF([e],{...n,width:1/0});return B(eF(r.flat()))<=n.width}function oW(e,t,n,r){if(aW(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=iW(n,r);return i.divide(rW(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 sW(e,t){let n=Math.max(2,lF(t)-oF(t)-t.padding);return cW(e,t).reduce((e,r)=>[...e,...oW(r,n,e,t)],[])}function cW(e,t){let n=()=>e.map(e=>({owner:tW(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=uF(e.map(tW),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(eF(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];ZU(c,c.cellLength+a,n)}),n()}function lW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=uW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:PP(a.style)};if(e.style.link){i();let r=uW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function uW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>dW(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 dW(e,t){let n=e.copy();return n.style=t,n}function fW(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function pW(e,t){let{look:n}=fW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function mW(e,t){let{layout:n}=fW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function hW(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 gW(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,_W(e,t,o,n,r,i));return i}function _W(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=Gx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=lx.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Gx(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=Gx(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:bW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:bW(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:Jx(n),argv:n.run.map(n=>bW(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,bW(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:bW(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 vW(e){return e.kind===`do`?vW(e.head):e}function yW(e){switch(vW(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 bW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function xW(e,t){return e.has(t)?YC(e.read(t)):``}function SW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function CW(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 wW(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([PP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([PP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function TW(e,t){return Math.max(e.members.indexOf(xW(t,e.stateVar)),0)}function EW(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=xW(r,e.stateVar);return{effects:[{verb:uS,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=xW(r,e.stateVar);return{effects:[{verb:uS,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=xW(r,e.stateVar);return{effects:[{verb:uS,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(TW(e,r)+1)%e.members.length];return{effects:[{verb:uS,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:dS,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:fS,args:[i,SW(e.text,bj(r))]}],active:!1};case`open`:return{effects:[{verb:pS,args:[i,SW(e.target,bj(r))]}],active:!1};case`persist-literal`:{let t=xW(r,e.stateVar);return{effects:[{verb:hS,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=xW(r,e.stateVar);return{effects:[{verb:hS,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(TW(e,r)+1)%e.members.length];return{effects:[{verb:hS,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:gS,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:xS,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:CS,args:[i]}],active:!1};case`redo`:return{effects:[{verb:wS,args:[i]}],active:!1};case`back`:return{effects:[{verb:TS,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ES,args:[i]}],active:!1};case`save`:return{effects:[{verb:_S,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:vS,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:yS,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:bS,args:[i,SW(e.name,bj(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:OS,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:kS,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:AS,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:MS,args:[i,e.line]}],active:!1};case`run`:{let t=bj(r),n=JSON.stringify({run:e.argv.map(e=>SW(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,SW(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:SS,args:[i,e.key,nz(e.op)]}],active:!1};case`do`:{let o=EW(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>EW(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:SS,args:[i,e.key,nz(r)]}],active:!1}}}}function DW(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:ia(`action "${e}"`,n,t.members.length,TW(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 OW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=fW(n,`action "${e}"`).store,{display:a,boundValue:o}=DW(e,vW(r),t,i),s=xW(i,`session.id`),{effects:c,active:l}=EW(r,a.plain,o,i,s,n.links.signer);return wW(a,GS(n.links.to,c),l)}function kW(e){return{action:{fn:(t,...n)=>OW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function AW(e,t,n){return CW(`✕`,GS(e,[{verb:uS,args:[xW(t,`session.id`),n,ea]}]),!1)}function jW(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(F_(e,t,n))})}function MW({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function NW(e,t,n){return new W({color:U.fromRgba(Iu(e.get(`warning`),t,P_,n))})}function PW(e,t,n){return W.combine([jW(e,t,n),NW(e,t,n)])}function FW(e,t,n){return MW(q_(e.palette,e.disclosure,t,n))}function IW(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(Lg.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const LW=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},RW=e=>new W({bold:e});function zW(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>LW(a,W.combine([FW(e,{...n,distribution:t},i),RW(o)]));let o=jW(e.palette,a,i);return(e,t,i,a)=>BW(i,W.combine([o,RW(a)]),r(t,n))}const BW=(e,t,n)=>LW(q.fromFragments([LW(e,t),LW(` `,t),IW(n)]));function VW(e,t,n,r){return t===void 0?LW(r):BW(r,void 0,t(n,e))}function HW(e,t,n,r,i){let a=jW(e.palette,i,r);return(e,r,i,o)=>LW(q.fromFragments([LW(o?`[`:` `,a),IW(n(r,t)),LW(o?`]`:` `,a)]))}function UW(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=>WW(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function WW(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function GW(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function KW(e){return{current:null,drawnAt:e}}function qW(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 JW(e,t,n){return XW(e,()=>n(qW(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function YW(e,t){return XW(e,()=>(e.current=null,t()))}function XW(e,t){let n=e.current;try{return t()}finally{e.current=n}}function ZW(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 QW(e){return new q(e).cellLength}function $W(e){let{width:t,chromeCols:n,padding:r}=fW(e,`a row fit`);return Math.max(1,t-n-2*r)}function eG(e){let{padding:t,seamCols:n}=fW(e,`a row fit`);return Math.max(1,$W(e)-(QW(`✕`)+2*t+n))}function tG(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 nG(e,t,n){let r=QW(`←`)+1+QW(`→`)+1,i=tG(e,t,n);return(i.length>1?tG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function rG(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 iG(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function aG(e,t,n){let r=e.compiled.get(t),i=r&&vW(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 oG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=fW(a,`picker`).store,d=xW(u,`session.id`),f=`stateVar`in t?xW(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`?eG(a):$W(a):1/0,h=(r.kind===`led`?0:QW(`✕`)+1)+c.reduce((e,t)=>e+QW(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?nG(v.map(e=>e.cellLength),m,h):UW(g.entries,g.groups,i),b=parseInt(xW(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>GS(a.links.to,[{verb:uS,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:uS,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ee=r.kind===`own`&&r.onPick?E:[],D=e=>GS(a.links.to,[...EW(l,e,e,u,d,a.links.signer).effects,...ee]),te=(e,n)=>wW(e,D(t.options[n])),O=r.kind===`led`?[]:[CW(`✕`,GS(a.links.to,E),!1,s)];O.push(...c.map(({glyph:e,option:r})=>CW(e,GS(a.links.to,[...EW(l,r,r,u,d,a.links.signer).effects,{verb:uS,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&O.push(CW(`←`,T(C-1),!1));let k=C<y.length-1?[CW(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[rG([...O,...e.map(e=>te(v[e],e)),...k])]}let ne=new W({bold:!0}),A=y.length>1?` ${C+1}/${y.length}`:``,re=w.length===1?[new q(`${w[0].label}${A}`,{style:ne})]:[],ie=[rG([...O,...re,...k])];for(let e of w){w.length>1&&ie.push(rG([new q(e.label,{style:ne})]));let n=Math.max(...e.indices.map(e=>QW(_(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:WP(i),o=` `.repeat(n-QW(e)+2),s=a===void 0?e:`${e}${o}${a}`;ie.push(rG([te(p(r,GW(s,m)),r)]))}}return ie}function sG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ej(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=iG(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=aG(e,n,`picker`),u=ZW(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=>oG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,zW(u,y_(void 0),pW(e,`{{ picker }}`),l.paletteOf,d,t),NW(u.palette,t,d)),p=G_(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 cG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function lG(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=fW(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=xW(a,`session.id`),{options:c}=t;if(c.length===0)return rG([]);let l=cG(c,xW(a,t.stateVar)),u=e=>c[l(e)],d=e=>GS(i.links.to,EW(o,u(e),u(e),a,s,i.links.signer).effects);return rG([CW(`◀`,d(-1),!1),wW(VW(pW(i,`{{ carousel }}`),t.paletteOf,u(0),r),GS(i.links.to,EW(i.compiled.get(n),u(0),void 0,a,s,i.links.signer).effects)),CW(`▶`,d(1),!1)])}function uG(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(yW(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 lG(t,aG(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function dG(e,t,n){let r=aG(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function fG(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 pG(e,t,n,r){let i=dG(e,t,n),a=r??xW(fW(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,pW(e,`{{ ${n} }}`))}function mG(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ej(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return IW(pG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function hG(e,t,n){return{swatches:{fn:(r,i)=>{let a=dG(e,r,`swatches`),o=iG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=ZW(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]=oG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,HW(s,pW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),NW(s.palette,s.bg,c),u===0?[]:(()=>{let t=cG(l,xW(fW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[fG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const gG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function _G(e,t,n,r){let i=G_(e,n,r),a=(t,n)=>({text:t,colour:n,ink:F_(e,n,r)});return[[a_(e,t,r).map((n,i)=>{let a=N_(e,n);return{text:gG[i%gG.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 vG(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:MW({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 yG(e,t,n,r,i){let a=_G(e,t,n,r).map(e=>vG(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
|
|
195
|
-
|
|
196
|
-
`)
|
|
197
|
-
`)){n.
|
|
198
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function HG(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 UG=e=>e.kind===`failed`?qU:e;function WG(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function GG(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 KG(e){return{...e,cells:e.cells.map($U)}}function qG(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,...JG(e,r)]}function JG(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 YG(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:qG(e.direction,e.children.map((t,i)=>n(t,[...r,XG(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function XG(e,t){return e.steps[t]}function ZG(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=QG(e);return{width:$G(t),reach:eK(t)}}function QG(e){let t=e.children.map(ZG),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 $G=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),eK=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function tK(e,t){let n=QG(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=Jv[e.direction],i=y_(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),eK(n),$G(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const nK={compile(e,t){let n=tK(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,ey(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),qG(e.direction,e.children.map((n,r)=>t.renderChild(n,UG(t.gate),XG(e,r))))}},rK={drop:e=>e.place,above:()=>`above`},iK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},aK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:Yv(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(sa(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,ty(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,oK(e,t))};function oK(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=Sj(t.scope,e.settings);if(t.gate.kind===`failed`)return fK(e,r,t,t.gate.message);try{let i=t.placement(e),a=WG(t.gate,i.gate());if(a.kind===`failed`)return fK(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 fK(e,r,t,s.message);let c=hx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:_P(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`?sK(f.variable):cK(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?lK(p.segment,u):uK(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:qU,h.disclosure).map(e=>({...e,place:rK[v.placement](e)})),b=(e,t,n)=>nW(lW([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?iK[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new q(` `.repeat(dK(QU(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],E=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),ee=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ee.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(QU)),[...ee,...E]}catch(n){return fK(e,r,t,n.message??String(n))}}const sK=e=>({kind:`waiting`,variable:e});function cK(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=$C(e);if(t===void 0)throw e;return sK(t.variable)}}function lK(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:VG(lW(r,c)).map((e,t)=>({cells:nW(e,{...l,lead:t===0?lW(i,c):[],trail:t===0?lW(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:nW(lW([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function uK(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=lW(pK(e.lead,e,t,n),l),d=lW(pK(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 nW(lW([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function dK(e){return e.reduce((e,t)=>e+t.cellLength,0)}function fK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:nW([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:_P(n.palette)},lead:pK(e.lead,e,t,n),trail:pK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function pK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=$C(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const mK={container:nK,segment:aK};function hK(e){return mK[e]}var gK=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?_K:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const _K={kind:`hidden`},vK={palette:`theme`,style:`style`,effect:`effect`},yK=lx.get(`colorCompatibility`),bK={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function xK(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function SK(e){if(e.ok)return e.value;throw e.error}const CK=e=>({read:()=>e}),wK=Fg({basePalette:Pg,palette:Pg,decor:X_});var TK=class{evaluated=0;memory=new gK;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&wK(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=bj(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(yK);return e.kind===`found`&&typeof e.value==`string`&&Pv(e.value)?e.value:`truecolor`});let i=(0,X.observable)(bK,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 YG(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=WR(e);return i===void 0?[]:[{name:i,address:n,palette:hx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Fv(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=BM(e);return t===void 0?RM(e)===void 0?DM(this.view.get().payload(),e):DM(this.projected,e):EM(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()[vK[e]];if(t.kind===`decided`)return OK(t.name,null,null);let r=AK(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=jK(this.source,e,i.name,r.where,e=>{t=e}),OK(n,t,null)}case`pending`:return OK(n??xv[e],null,i.variable);case`failed`:return n=xv[e],OK(n,Sv(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!kK(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)??xv[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return YU(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>YW(this.source.activeSegment,()=>YU(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new MK(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:hW(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=$C(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:xK(e)}),SK(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:WR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function EK(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new TK(t,n,e,r);return e.views.set(t,a),a}function DK(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 OK=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),kK=(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 AK(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 jK(e,t,n,r,i){switch(t){case`palette`:return yx(n,r,i).name;case`style`:return vv(n,e.styles).name;case`effect`:return Ov(n).name}}var MK=class{where=NK(Fg({palette:Pg,region:J_}));ground=NK(Fg({colours:FK,bodyOpen:Pg}));opened=NK(Fg({colours:FK,open:Pg}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Sj(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?CK(JU):e.derive(`${t.id} when`,e.readsInstant(a),()=>YW(r,()=>YU(a,i))),this.open=d===void 0?CK(qU):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>YW(r,()=>YU(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return RK(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 zK(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?CK(VK):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return BK(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}),UK(n,r,this.affixes.read())}};function NK(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const PK=(e,t)=>e.hex===t.hex,FK=Fg({palette:Pg,drawnAt:Pg,tint:PK,text:PK,bg:PK,disclosure:Z_});function IK(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const LK=e=>G_(e.palette,e.disclosure,e.drawnAt);function RK(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...rv(n,r,i)};return JW(e,IK(t,c),e=>{let t=Fte(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function zK(e,t,n,r,i,a){return JW(e,IK(t,n),e=>(e.bg=i?LK(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function BK(e,t,n,r,i,a,o){return JW(e,IK(t,n),e=>(e.bg=r?LK(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const VK={lead:[],trail:[],drops:[]};function HK(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return jW(t,LK(e).state,n)},get band(){return jW(t,LK(e).plane,n)},get close(){return PW(t,LK(e).state,n)},disclosure:r}}function UK(e,t,n){return{styles:HK(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function WK(e,t,n,r,i,a,o){let s=RK(e,t,n,r,i,void 0,void 0,o);return UK(s,zK(e,t,s,a,!1,o),VK)}function GK(e,t,n,r,i){return HK(RK(e,t,n,r,i,void 0,void 0,{}))}function KK(e,t){return{payload:()=>e,selections:()=>t}}function qK({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),[...[...Yx(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=vC(e=>{let i=jC(e,t)?Object.keys(n):DC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=vC(n=>i(n).flatMap(n=>[...CC(n,t).keys()].map(t=>({path:t,reaches:BC(t,e)}))));return{ofTemplate:a,calls:vC(e=>new Set(i(e).flatMap(e=>[...NC(e,t)]))),ofVariable:t=>[...cy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...oy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function JK(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const YK=new WeakMap;function XK(e){let t=YK.get(e);return t===void 0&&(t=qK({names:new Set([...zC(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),YK.set(e,t)),t}function ZK(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 QK=new WeakMap;function $K(e){let t=QK.get(e);return t===void 0&&(t=tq(e),QK.set(e,t)),t}function eq(e){return $K(e).projections}function tq(e){let t=new Map(zC(e)),n=new Map,r={reads:XK(e),projections:n,clock:_j};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=JK(e,r),i=t===void 0?null:RM(t);i&&n.set(e,`reads the draw's "${i}" (${LM[i]})`)}let i=rq(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=ZK(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of pv)if(!a.has(t))for(let n of i[t]){let i=ZK(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=JK(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 nq(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>pv.flatMap(n=>{let r=t[n];return mv(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function rq(e){let t=nq(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function iq(e,t){return ZK(e,$K(t))}function aq(e){return t=>ZK(t,e)!==null}function oq(e){if(`ttl`in e)return{kind:`ttl`,durationMs:SM(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 sq(e,t){switch(iy(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 cq(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:oq(n.cache),parse:sq(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:oq(n.cache),parse:sq(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 lq(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 uq(e,t,n){let{compiled:r,loadWarnings:i}=fq(e,t,n.cwd,dq(n.links),gq);return{...r,loadWarnings:i}}const dq=e=>(t,n)=>_q(n,e);function fq(e,t,n,r,i=gq){let a=pq(e),o=mq(a);return{compiled:r(o,a),compileKey:o,loadWarnings:hq(e,t,n,i)}}function pq(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of ux)n in t&&r.set(e,n);for(let[t,n]of dy(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...eq(e)].sort(([e],[t])=>e<t?-1:1)}}function mq(e){return ce(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function hq(e,t,n,r){let i=BG(e),a=eq(e),o=[];for(let[s,c]of zC(e))if(r.has(i.get(s)))try{cq(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const gq=new Set([`directory`,`view`]);function _q({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,links:r},a=()=>fW(i,`drawnAt`).registry.drawnAt(),o=KW(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Fx(e.presets),u=NR(e),d=[e=>hG(i,o,e.now)],f=yj({extraFuncs:{...kW(i),...mG(i),...sG(i,o),...uG(i),...bG(i,o),...EG(i,o),...AG(s),...NG(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=lq(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=gW(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:lq(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=hy(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>xy(t,e,a,t=>String(fW(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 hK(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Rx(e,t);C.set(t,S(n,r,void 0))}let w=new Map(pv.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of nq(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:bq(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),E={reads:qK({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:vj(d)},ee=aq(E),D=[...C.values()].flatMap(yq(y)).some(e=>ee(m.get(e))),te=D?new Set([...E.clock,TG]):E.clock,O=aq({...E,clock:te}),k=new Set([...m].flatMap(([e,t])=>O(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=aq({reads:qK({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:E.projections,clock:te});for(let e of CH){let n=y[t][e];n!==void 0&&r(m.get(n))&&k.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,links:r,globalExpressions:w,instant:k,layoutReadsInstant:D,styles:e.styles,runtime:i,views:new WeakMap}}function vq(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 yq=e=>t=>{let n=[];return YG(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 bq(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 xq=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function Sq(e,t,n,r,i){let a=Cq(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function Cq(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??xv[e];case`failed`:return r({kind:`rule`,slot:e,message:Sv(t.where,e,`the rule failed — ${n.error}`)}),xv[e]}}function wq(e){return Tq(e).filter(e=>!e.name.startsWith(eS)).map(e=>e.id)}function Tq(e){return e.kind===`container`?e.children.flatMap(Tq):[e,...e.opens===void 0?[]:Tq(e.opens.body)]}function Eq(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return EK(e,t,n,KK(o,a)),o}function Dq(e,t,n,r,i,a,o,s,c){try{var l=uo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new BP(``),h=m.clockAt(a,wv[c.animationSpeed]),g=l.u(cj(a,h.timeline)),_=DK(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:oF(v),padding:v.padding,seamCols:sF(v),preset:c.preset},i);let y=_.evaluated;l.u(hW(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:r_[c.variation],shade:Jg[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,GG),T=_.memory.from(C),E=new Set,ee={held:e=>T?.rules.get(e),waited:e=>E.add(e),settled:w.rule},D=new Map,te=e=>{let n=_.slot(e);if(D.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&&E.add(n.waited),n.name;let r=jK(t,e,Sq(e,n.rule,_,p,ee),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:O,style:k,effect:ne}=_.selections(),A=O.kind===`decided`?O:yx(te(`palette`),``,xq),re=k.kind===`decided`?k:vv(te(`style`),e.styles),ie=ne.kind===`decided`?ne:Ov(te(`effect`)),ae=A.value,oe=_x(ae,re.value);_.publishLook({basePalette:ae,palette:oe,decor:S});let se=oe.get(`warning`),ce=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:se,text:F_(oe,se,r.drawnAt())},le=m.motion(ie.value,h,{transitions:x,source:C,last:T,returned:GG,hold:KG},ce);u?.clear();let ue=t=>e.segments[t],de=(e,i,a)=>{let o=i.kind===`hidden`?i:WG(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${wq(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:oe,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>WK(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:ue,renderChild:(e,t,n)=>de(e,t,tv(a,n)),renderBody:(e,t,n)=>de(e,t,nv(n)),closeDisclosure:e=>AW(t.links.to,n,e),placed:(e,t)=>w.placed(e,le.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>E.add(e),decorations:(e,n)=>GK(t.activeSegment,e,n,a,r.drawnAt())};return hK(e.kind).render(e,c)},fe=t.roots.get(b);if(fe===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Px}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let pe=HG(de(fe,JU,ev(S))).map(({line:e,row:t})=>{let n=sW(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...uF(n.map(e=>e.owner),v,le.row(t,r,n))}});le.drawn(),w.commit();let me=()=>pe.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||Tq(fe).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),he=Math.min(g.heard(),...pe.map(e=>e.nextChange)),ge=Number.isFinite(he)?`moves`:me()?`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:pe.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:he,motion:ge,pending:[...E].sort()},evaluated:_.evaluated-y,cellBreaks:pe.reduce((e,t)=>e+t.cellBreaks,0),rules:D}}catch(e){l.e=e}finally{l.d()}}function Oq(e){return Math.max(1,e-2)}function kq(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function Aq(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const jq={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},Mq={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Nq(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const Pq={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function Fq(e){return Object.keys(Pq).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${Pq[t]}: ${n.reason}`]:[]})}function Iq(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(Lq(e,t),`read`)}function Lq(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Rq(t.stderr)].filter(Boolean).join(`, `)}`}function Rq(e){return e.trim().split(`
|
|
199
|
-
`,1)[0]??``}function zq(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function Bq(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const Vq={github:`gh`,gitlab:`glab`};function Hq(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const Uq=/^[A-Za-z]:[\\/]/;function Wq(e){let t=e.trim();if(Uq.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 Gq(e){return Wq(e)?.host||null}function Kq(e){let t=Gq(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const qq=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function Jq(e){let t=Iq(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?Yq(t.value):[]}}function Yq(e){let t=new Map;for(let n of e.split(`
|
|
200
|
-
`)){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 Xq(e){return e.urls.find(e=>tJ(e)!==null)??e.urls[0]??null}function Zq(e){return e.find(e=>e.name===`origin`)??e[0]??null}function Qq(e){let t=Zq(e);return t?Xq(t):null}function $q(e){let t=Zq(e);return t?t.urls.find(e=>Kq(e)!==null)??Xq(t):null}function eJ(e){let t=(Wq(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function tJ(e){let t=Wq(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 nJ(e){let t=Qq(e);return t===null?null:tJ(t)}function rJ(e,t,n,r){return t.ok?r(t.stdout):Hq(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Rq(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function iJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aJ(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
201
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function oJ(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!iJ(t))return L(`gh pr view: JSON is not an object`,`parse`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`,`parse`);let o=Nq(`gh pr view`,jq,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function sJ(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!iJ(t))return L(`glab mr view: JSON is not an object`,`parse`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`,`parse`);let o=Nq(`glab mr view`,Mq,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function cJ(e){try{let t=h.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var lJ=class{constructor(e){this.launcher=e}isGitRepo(e){return tc(e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=nc(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`,`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=zq(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=zq(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=zq(s,nJ)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){return ao(sc(e),s.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return h.existsSync(s.join(t,`MERGE_HEAD`))?F(`MERGE`):h.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):h.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):h.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):h.existsSync(s.join(t,`rebase-merge`))||h.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async getNearestTagAsync(e){return Bq(Iq(`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=Bq(Iq(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`,`parse`):F(r)}resolveCommonGitDir(e){return ao(cc(e),e)}getStashCount(e){let t=s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=h.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return F(r?r.split(`
|
|
202
|
-
`).length:0)}async getRemotesAsync(e){let t=cJ(s.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 Jq(await this.execGitAsync(qq,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=Qq(e);return(n===null?null:eJ(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=$q(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=Kq(t);return n===`github`?rJ(`gh pr view`,await this.execForgeAsync(Vq.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,oJ):n===`gitlab`?rJ(`glab mr view`,await this.execForgeAsync(Vq.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,sJ):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(h.existsSync(t)&&h.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){Pe(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=Iq(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(aJ(t.value)):t}};const uJ=`#/definitions/LayoutNode`,dJ={kind:`container`,direction:`vertical`,children:[]};function fJ(e){return{required:!0,json:{const:e},parse:()=>e}}function pJ(){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 ${Y(i)}`,line:J(e.source,[`root`])}),``)}}}function mJ(){return{required:!0,json:{enum:[...qv]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&qv.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${qv.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function hJ(e){return{required:!0,json:{type:`array`,items:{$ref:uJ}},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 ${Vy(a)}`,line:J(t.source,[`root`])}),[])}}}const gJ={noun:`layout-node key`,fields:{kind:fJ(`segment`),name:pJ(),when:$y(),id:qB(),settings:JB()}},_J=()=>sb(g_),vJ={noun:`layout-node key`,fields:{kind:fJ(`container`),direction:mJ(),children:hJ(Zy(()=>CJ)),when:$y(),distribution:_J()}};function yJ(){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 ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])}),``)}}}const bJ={noun:`layout-node key`,fields:{seg:yJ(),when:$y(),id:qB(),settings:JB()}},xJ={noun:`layout-node key`,fields:{h:hJ(Zy(()=>CJ)),when:$y(),distribution:_J()}},SJ={noun:`layout-node key`,fields:{v:hJ(Zy(()=>CJ)),when:$y(),distribution:_J()}},CJ=(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`])}),dJ):{kind:`segment`,name:n};if(!Wv(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 ${Vy(n)}`,line:J(e.source,[`root`])}),dJ;if(n.kind===`container`)return Hy(e,vJ,t,n)??dJ;if(n.kind===`segment`)return Hy(e,gJ,t,n)??dJ;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
190
|
+
`,SP=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function Vte(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function CP(e,t,n){return s.resolve(e,Vte(t,n))}function wP(e,t,n){return typeof t==`string`&&t!==``?CP(e,t,n):void 0}const TP=`CC_CANDYBAR_CONFIG`;function EP({env:e,home:t},n){return wP(n,e[TP],t)}function DP(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function OP(e,t,n){return DP(wP(n,e,t.home),EP(t,n))}function kP(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const AP=new rf({"strip.separator":`default`,"strip.rail":`default`});function jP(e){return AP.resolve(e)}const MP={kind:`still`},Hte=e=>rp.at(e.timeline,e.wall),NP=Symbol(`bar`);function Ute(e){return e.name!==vv}function Wte(e){return t=>K.map(K.all(e.map(({timeline:e,effect:n})=>rp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const PP=Tee;function Gte(e,t){let n=new Gl(t,PP.foregroundColor,PP.ansiColors,PP.palette);return t=>e({...t,theme:n})}function Kte(e,t){return n=>Xm(()=>e(n),...t)(n)}function FP(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 IP=4096;function qte(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=wb.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 LP=class{inForce=null;anchor=rp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:vv,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:rp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=Hte(t),a=e=>rp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:NP,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=Zh.transitions[e]({z:FP(`${this.key}@${t}`)*IP});return{name:e,since:i,done:e=>r.done(e),effect:Gte(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},E=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},ee=(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}},D=(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=FP(t.scope===NP?e:`${e}@${t.scope}`),s=a?i.effect:Zh.loops[t.name]({z:o*IP});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ee(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()]},O=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:Xm(n.effect,...t)}]})},k=r===null?[]:[{timeline:rp.play(r.idleSince),effect:qte(r.fill,r.text,Ob(r.timeoutS))}],ne=e=>e===`menu`?k:[];return{placed:h===`off`?(e,t)=>t:E,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?te(r):[{...s,owners:void 0}]).filter(Ute),o=O(r),c=ne(n);if(i.length===0&&o.length===0&&c.length===0)return MP;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new Gm(e,Wte([...i.map(e=>{let t=D(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:Kte(t,e.owners)}}),...o,...c]),{key:l,theme:PP})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},Jte=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new LP(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 RP={fg:`#ffffff`,bg:`#c82828`},zP={fg:`#000000`,bg:`#dca028`};function BP(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const Yte=BP(38,RP.fg),Xte=BP(48,RP.bg),Zte=[[0,31],[127,159],[8234,8238],[8294,8303]];function Qte(e){return Zte.some(([t,n])=>e>=t&&e<=n)}function VP(e){let t=``;for(let n of e)t+=Qte(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function HP(e,t){let n=VP(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const $te=`${Xte}${Yte}`;function UP(e){return`⚠ cc-candybar: ${tne(e)}`}function ene(e){return`${$te}${UP(e)}[0m\n`}function tne(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: ${HP(e.message,60)}`;case`render_failed`:return`render failed: ${HP(e.message,60)}`;case`switched_off`:return`switched off: ${HP(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${HP(e.message,60)}`}}function WP(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function GP(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:VP(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function nne(e){return GP(UP({kind:`permanent`,cause:`render_failed`,message:e}),RP)}function KP(e,t){try{return e(t)}catch(t){return e(GP(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,RP))}}function qP(e){return e.type===H.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const rne=Object.keys(new W().attributes);function ine(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=rne.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:qP(n)},...r!==void 0&&{bg:qP(r)},...i.length>0&&{attrs:i}}}function ane({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&ine(t,n),...t?.link!==void 0&&{link:t.link}}}function one(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return G.splitLines(n).map(e=>e.map(e=>ane(e,t)))}function sne({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 JP(e,t){let n=Sl(t);return e.map(e=>Wm(e.map(sne),n)).join(`
|
|
191
|
+
`)}function YP(e){return JP(e.rows.map(e=>e.runs),e.depth)}function cne(e){return YP(e)+`
|
|
192
|
+
`}const lne=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function XP({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&lne(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function ZP(e){return e.map(e=>e.text).join(``)}const une={};function QP(e,t){let n=Sl(t.colorSystem),{time:r}=t,i=1/0,a=[...kf(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:AP,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:une}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:one(a,n.colorSystem),nextChange:Math.min(G.nextChange(a),i)}}const $P=new Map;function dne(e){let t=$P.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}=Vm.plain,a=new dm({glyph:n(r.glyph),ascii:r.ascii},i);return $P.set(e,a),a}function eF(e,t){return e===`plain`&&t!==void 0?dne(t):Vm[e]}const tF=new Map;function nF(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=tF.get(t);if(n!==void 0)return n;let r=eF(e.endcaps,e.separator),i=e=>new q(`x`,{end:``,overflow:`ignore`,style:new W({bgcolor:e})}),a=e=>{let{lines:t}=QP(new Pp(e,r),{colorSystem:null});return new q(ZP(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return tF.set(t,s),s}function rF(e){return nF(e).chrome}function iF(e){return nF(e).seam}const fne=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function aF(e){return[...new Set(e.match(fne)??[])].join(``)}function pne(e){let t=eF(e.endcaps,e.separator),n=e=>new q(`x`,{end:``,style:new W({bgcolor:e})}),{lines:r}=QP(new Pp([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return aF(ZP(r.flat()))}function oF(e){return e.wrap?e.width:1/0}function mne(e,t){return QP(new q(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(ZP)}function sF(e,t,n=MP){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=eF(t.endcaps,t.separator),i=Number.isFinite(oF(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new Ag([...e],{joiner:r}):new Pp([...e],r),s=n.kind===`still`?QP(o,a):QP(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function hne(e,t){return JP(sF(e,t).lines,t.colorCompatibility)}const gne=[`moves`,`can-move`,`still`];function cF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const _ne=[`statusline`,`frames`],lF=e=>e?.kind===`frames`?`frames`:`statusline`,vne=[`carried`,`missing`,`unanswered`];function yne(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:cF(e)===`no`?`unanswered`:`missing`}function bne(e){return{path:e.transcript_path,answered:cF(e)===`yes`}}const uF=[...gne,`failed`,`drawing`];var xne=class{seen=new Map;see(e,t,n,r){let i=lF(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 dF={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`}}},fF=e=>dF[e];function Sne(e){return fF(e).glyphs.kind===`bundled`}function Cne(e){return fF(e).glyphs.kind===`configured`}const pF=e=>fF(e).label,wne=[{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 Tne(e,t){let n=t.codePointAt(0);return wne.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&gF(e,t)===!0)}const mF=Object.keys(dF);function hF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function gF(e,t){let n=hF(e),r=hF(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 Ene(e){for(let t of mF){let n=fF(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 _F(e){let t=mF.find(t=>fF(t).term===e);return t===void 0?null:{name:t,version:null}}function Dne(e){let t=Ene(e.termtype)??_F(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 One(e){let t=e.TERM_PROGRAM,n=mF.find(e=>fF(e).program===t),r=n===void 0?_F(e.TERM):{name:n,version:fF(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 vF(e){switch(e.kind){case`known`:return pF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function yF(e){switch(e.kind){case`known`:return pF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function kne({name:e,version:t}){let n=fF(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=gF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Ane=mF.filter(e=>fF(e).links!==null).map(pF).join(`, `);function bF(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(!Ho(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||!Ho(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function xF(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 jne=[`managed`,`project`],Mne=e=>!jne.includes(e.scope),Nne={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:zo(t.projectDir)}),user:e=>({scope:`user`,path:e})},SF=[`drawn`,`boxes`],CF=1024*1024,wF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function Pne(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 TF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const EF=pc.truecolor;function DF(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 Fne={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>DF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=xF(t.sources,EF);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:`${EF} 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`,EF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Nne[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 ${EF} to "1" there`}:o(s)})},Ine={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>DF(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"})},Lne={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:`${wF(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 ${wF(e.value.of)} measured`}},Rne={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},zne={argument:`command argument`,environment:`$${TP}`,unknown:`source unknown`};function Bne({target:e,layers:t}){return e.source===`search`?t.length===0?kP(t):`${kP(t)} (searched)`:`${e.path} (${zne[e.source]})`}function Vne(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
193
|
+
`).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 Hne={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=Bne(e),n=TF(Vne(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},OF="re-run `cc-candybar install`";function Une(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:// — ${OF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${OF}`]}function Wne(e){return e===null?[]:[`the daemon (${e.theirs}) is another build than this client (${e.mine}), so it may not read the link this build sends`]}const Gne={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 — ${OF}`};case`lost`:return TF([...Une(e.opener),...e.unopened===null?[...Wne(e.otherBuild),`a cc-candybar:// link was opened and did not arrive at the daemon`]:[`a cc-candybar:// link could not be opened — ${e.unopened}`]])}}};function kF({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 AF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${mb.join(`|`)}>\``:e.checkout===null?OF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Kne(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 — ${AF(e,`native`)}`];let{bundle:i,source:a}=kF(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} — ${AF(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 — ${AF(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 jF=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)`},qne={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`:`${jF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:TF([...new Set(i.flatMap(e=>Kne(n,r,e)))])}};function MF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||yi(e.identity,t.value.through)):[]}function NF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Jne={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`?NF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return TF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=MF(e.value,n),u=TF([...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 ${P(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 ${P(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Si(o.charge.bytes,s)?[`the daemon holds ${Ei(o.charge)} of its ${P(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}}}},PF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Yne(e,t){let n=vF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?kne(e.terminal):{kind:`unknown`}}function Xne({identified:e,tmuxClient:t},n){let r=yF(e),i=Yne(e,n),a=vF(e)===null?PF:`${PF}, 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: ${Ane}`];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 Zne={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 TF(Xne(t,n))}}},FF=e=>e.filter(e=>e.role===`statusline`),Qne={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})=>ere(e,$ne(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:IF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:jF(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}}},$ne=e=>{let t=FF(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`}},IF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function ere(e,t){let n=bF(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 IF(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 Mne(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 LF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function tre(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return yF(e);case`bundling`:case`unread`:case`configured`:return[pF(e.name),e.version].filter(e=>e!==null).join(` `)}}function nre(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return vF(e);case`bundling`:case`unread`:return pF(e.name);case`configured`:{let t=pF(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 RF(e){let t=nre(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${LF(e.glyphs)}`}}const zF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=RF(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=tre(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 ${LF(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=dF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:gF(i.version,e);if(t===!0)return{ok:!0};let n=pF(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 ${LF(n)} — set a Nerd Font as its font`)}}}};function BF(e){return e.join(`, `)}function VF(e){return`or set missingData: "ignore" on ${BF(e)}`}function HF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${BF(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`?[`${BF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${VF(t)}`]:[`${BF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${VF(t)}`]}function UF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${BF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${BF(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`:`${BF(n)}: ${jF(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`)?[`${BF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${BF(n)}`]:[]}const WF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>TF([...HF(e.pullRequests),...UF(e.rateLimits,t)])};function GF({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 ${CF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const KF=[Hne,qne,Jne,Gne,Zne,Fne,Ine,Lne,Qne,zF,WF,{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`:`${jF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:TF(e.value.flatMap(GF))}],qF=KF.filter(e=>e.takesMark);function JF(e){return KF.map(t=>({check:t,verdict:t.probe(e)}))}function YF(e){return KF.find(t=>t.name===e)}const XF=`${Qx}doctor.`;function ZF(e){let t=`${XF}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function QF({target:e}){return`configTarget=${e.source}`}function $F(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?vF(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 eI(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 tI(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}=kF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const nI=e=>`${e>=0?`+`:``}${P(e)}`;function rI({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${NF(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`:`${MF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Di(i.charge)}${i.charge.kind===`stand-in`?`(${nI(-i.charge.gap)})`:``}:${P(i.charge.bytes)}`}/${P(a)} postMortems=${s}`}function iI(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 aI(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>oI(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=FF(r.flatMap(e=>e.bars));return`frames=${uF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function oI(e){let t=bF(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 sI(e){let t=xF(e,EF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function cI(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 lI(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=RF(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 uI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function dI(e){return e.flatMap(({check:e,verdict:t})=>{let n=ZF(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Lv},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:uI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Lv:Iv},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const fI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function pI(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(fI).map(([t,n])=>[`${e}${t}`,n]))}}const mI=`armed`,hI=`disarmed`,gI=`.armed`,_I=e=>e.endsWith(gI);function vI(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 yI(e,t,n){let r=`${e}${gI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${mI}")`,s=vI(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:mI},[a]:{set:r,to:hI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:hI}},disarm:a}}const bI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function xI(e){return typeof e==`string`&&bI.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 SI(e){let t=xI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const CI=[`/compact`,`/model`],wI=`/clear`;function TI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=yI(`${e}clear`,{arm:wI,confirm:`${wI} ✓ confirm`},[{action:n,when:`true`}]);return{template:CI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${fb} }}`,actions:{...Object.fromEntries(CI.map(e=>[t(e),{slash:SI(e)}])),...r.actions,[n]:{slash:SI(wI)}},variables:r.variables,disarm:r.disarm}}const EI=Array.from({length:10},(e,t)=>(t+1)*1e5),DI=EI[0],OI=EI[EI.length-1];function kI(e){let t=Io(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=DI&&n<=OI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${DI}–${OI} tokens)`,`parse`)}function AI(e,t){let n=Math.min(t??OI,OI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:EI.filter(e=>e<r).at(-1)??0,higher:EI.find(e=>e>r&&e<=n)??0}}function jI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${fb} }}{{ 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:SI(`/autocompact auto`)},...Object.fromEntries(EI.map(t=>[`${e}${t}`,{slash:SI(`/autocompact ${t}`)}]))}}}const MI=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 }}`,NI=`${Qx}edit`,PI=`${Qx}toolbar`,FI=pI(Qx),II=`${Qx}commands`,LI=TI(`${II}.`),RI=`${Qx}autocompact`,zI=jI(`${RI}.`,MI),BI=e=>({kind:`segment`,name:e}),VI=`${Qx}tab`,HI=e=>`${VI}.${e}`,UI=e=>`${HI(e)}.toggle`,WI=e=>({variable:VI,key:VI,member:e}),GI=`${Qx}save`,KI=`${Qx}preset.save`,qI=`${Qx}preset.delete`,JI=e=>`${Qx}${e}`,YI=e=>`${Qx}apply.${e}`,XI=e=>`${Qx}reset.${e}`,ZI=`${Qx}themeDefault.save`,QI=`${Qx}themeDefault.differs`,$I=`${Qx}themeDefault.theme`,eL={when:`{{ .${QI} }}`,template:`{{ action "${ZI}" (printf "⤓ default for %s" .${$I}) }} {{ swatch "${YI(`theme`)}" .${$I} }}`},tL=`${Qx}resetAll`,nL=`${tS}.toggle`,rL=`${Qx}undo`,iL=`${Qx}back`,aL=`${iL}.step`,oL=`${Qx}navigation.back`,sL=iL,cL={template:`{{ if gt .${oL} 0 }}{{ action "${iL}" "◁" }}{{ else }}{{ fg (${SP}) "◁" }}{{ end }}`},lL=`${Qx}redo`,uL=`${Qx}doctor`,dL=`${uL}.run`,fL=e=>`${uL}.fix.${e}`,pL=(e,t)=>`${uL}.mark.${e}.${t}`,mL=e=>`${uL}.${e}`,hL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},gL=UM(`${Qx}pickers`),_L=e=>`${Qx}${e}`,vL=e=>`${_L(e)}.toggle`,yL=e=>cN(e)?UM(`${Qx}${e}Pickers`):gL,bL=e=>{let t=yL(sN[aN[e].beside]);return{variable:t,key:t,member:e}},xL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${qI}" (printf "🚮 delete %s" .${nx.preset.effectiveVar}) }}`}},SL=(e,t)=>`${Qx}list.${e}.${t}`,CL=e=>`${Qx}resettable.${e}`,wL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${CL(e.name)})`).join(` `)})`,TL=mb.map(e=>[pb[e].switch.setting,e]),EL={variables:{},actions:{},segments:{}},DL=Object.fromEntries(TL.map(([e,t])=>[e,fP(`${Qx}help.${e}`,xP[t],[],EL)])),OL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],kL=e=>{let t=t=>`.${yb(e,t)}`,n=OL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${nx[pb[e].switch.setting].effectiveVar} ${JSON.stringify(pb[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},AL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${iS}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,jL=`${Qx}fps`,ML=`{{ if eq .${_b(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${_b(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,NL=Object.fromEntries(TL.map(([e,t])=>[e,kL(t)])),PL=e=>oN.filter(t=>aN[t].beside===e),FL=Object.keys(nx).map(e=>{let t=nx[e],n=sN[e];return{...t,name:e,place:n,control:tN({label:t.label,domain:hN(t.configKey)},t.sessionKey,t.effectiveVar,YI(e),yL(n)),beneath:t.previews.map(e=>xL[e]),help:[DL[e]].filter(e=>e!==void 0),submenus:PL(e)}}),IL=e=>FL.filter(t=>t.place===e),LL=e=>FL.filter(t=>lN(t.place,e)),RL=e=>t=>`(print ${da(t)} (ternary ${da(` •`)} "" ${wL(LL(e))}))`,zL=e=>IL(e).flatMap(e=>[ZL(e),...e.help,...e.submenus.map(e=>oa(_L(e),bL(e),iR(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(FL.flatMap(e=>[e.sessionKey,e.configKey]));const BL=yI(tL,{arm:`⟲`,confirm:`⟲ reset all?`},FL.map(e=>({action:XI(e.name),when:e.shown}))),VL=[`unsaved`,`history.undo`,`history.redo`],HL=e=>`${Qx}${e}`,UL=HL(`unsaved`),WL=(e,t)=>({body:t,shown:`(gt .${HL(e)} 0)`}),GL=[WL(`unsaved`,`{{ action "${GI}" (printf "💾 save %d" .${UL}) }}`),WL(`history.undo`,`{{ action "${rL}" "↶" }}`),WL(`history.redo`,`{{ action "${lL}" "↷" }}`),{body:BL.template,shown:`(or ${wL(FL)} ${BL.armed})`}],KL={when:`{{ or ${GL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+GL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},qL=[{step:BL,place:`door`},{step:LI,place:`session`}],JL=e=>e.map(e=>e.step.disarm),YL=JL(qL),XL=JL(qL.filter(e=>e.place!==`door`));function ZL(e){let t=JI(e.name);return e.control.kind===`inline`?BI(t):oa(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>BI(SL(e.name,n)))},`drop`)}function QL(e){return e===tS}function $L(e){let t=BI(tS);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[$L(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 eR(e){return tR(e)>0?e:$L(e)}function tR(e){let t=0;for(let n of Zv(e))n.kind===`segment`&&QL(n.name)&&(t+=1);return t}function nR(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&QL(e.name)||e.opens!==void 0&&nR(e.opens.body,!0):e.children.some(e=>nR(e,n))}const rR={door:{direction:`horizontal`,content:[BI(sL)],after:[BI(NI),BI(GI)]},session:{direction:`vertical`,content:[BI(PI),{kind:`container`,direction:`horizontal`,children:[BI(II),BI(RI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[BI(KI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[BI(uL),...KF.map(e=>BI(mL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[BI(ZI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function iR(e){let{direction:t,content:n,after:r}=rR[e];return{kind:`container`,direction:t,children:[...n,...zL(e),...r]}}function aR(e){return e.kind===`segment`?QL(e.name)?{kind:`container`,direction:`horizontal`,children:[oa(e.name,rS,sR,`above`),BI(jL)]}:e:cR(e)}function oR(){return{kind:`container`,direction:`vertical`,children:[iR(`door`),{kind:`container`,direction:`horizontal`,children:rN.map(({member:e})=>oa(HI(e),WI(e),iR(e),`drop`))}]}}const sR=oR();function cR(e){return{...e,children:e.children.map(e=>aR(e))}}function lR(e){let t={variables:{[tS]:fa(tS,ea),[iS]:{kind:`state`,key:iS,default:`0`}},actions:{[nL]:pa(tS,nS),[iS]:{set:iS,int:!0},[tS]:{do:[nL,...YL]},[dL]:{doctor:`run`},...FI.actions,...LI.actions,...zI.actions,[GI]:{save:!0},[rL]:{undo:!0},[aL]:{back:!0},[iL]:{do:[aL,...YL]},[lL]:{redo:!0},[KI]:{preset:`save`},[ZI]:{themeDefault:`save`},[qI]:{preset:`delete`,name:`{{ .${nx.preset.effectiveVar} }}`}},segments:{[tS]:{template:`{{ $door := ${ua(tS,da(e),da(`✖`))} }}{{ if ${ca(rS)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+AL},[jL]:{template:ML},[PI]:{template:FI.template},[II]:{template:LI.template,when:LI.when},[RI]:{template:zI.template,bg:zI.bg,when:zI.when},[sL]:cL,[GI]:KL,[ZI]:eL,[KI]:{template:`{{ action "${KI}" "+ preset" }}`},[uL]:{template:`{{ action "${dL}" "🩺 doctor" }}`},[NI]:{template:`{{ action "${aP}" "✎ arrange" "✎ done" }}`}}};t.variables[QI]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[$I]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[oL]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of VL)t.variables[HL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[VI]=fa(VI,ea);for(let{member:e,label:n}of rN){t.actions[UI(e)]=pa(VI,e),t.actions[HI(e)]={do:[UI(e),...XL]};let r=RL(e);t.segments[HI(e)]={template:`{{ ${ua(HI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,LI.variables,BL.variables),dR(t),uR(t),t}function uR(e){for(let t of KF){let n=ZF(t.name),r=fL(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?SF:[];for(let n of i)e.actions[pL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${pL(t.name,e)}" "${hL[e]}" }}`).join(``);e.segments[mL(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} "${Iv}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function dR(e){for(let t of FL){Object.assign(e.actions,t.control.actions);let n=XI(t.name);e.actions[n]={reset:t.configKey},e.variables[CL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${CL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[JI(t.name)]={template:`${t.control.template}${NL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[SL(t.name,r)]=n})}Object.assign(e.actions,BL.actions),Object.assign(e.variables,EL.variables),Object.assign(e.actions,EL.actions),Object.assign(e.segments,EL.segments);for(let t of oN){let n=bL(t);e.actions[vL(t)]=pa(n.key,n.member),e.segments[_L(t)]={template:`{{ action "${vL(t)}" ${RL(t)(aN[t].trigger)} }}`}}}function fR(e){let{variables:t,actions:n}=dP();Object.assign(e.variables,t),Object.assign(e.actions,n)}function pR(e){let t=lR(e.globals.menuGlyph??`🍫`);fR(t);let n={...e.presets},r=[];for(let t of Mx(e.presets)){let{node:i}=Fx(e,t),a=aR(eR(i));r.push(a),n[t]={...Px(e.presets,t),root:a}}let i=zM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const mR=`${Zx}live`,hR=[`☐ live`,`☑ live`],gR=`${Zx}done`,_R=`${Zx}cancel`,vR=`${Zx}rewind`,yR=`${Zx}changes`,bR=`(gt .${yR} 0)`,xR=`(or ${bR} (gt .${UL} 0))`,SR={variable:mR,key:mR,member:ta};function CR(e){return`${Zx}configuring.p${e}`}function wR(e){return`and ${ca(lP)} (not ${ca(SR)}) (ne .${CR(e)} "true")`}function TR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${iP} "${aa(e)}")`).join(` `)} false }}`}}function ER(e,t,n){return`{{ if ${wR(e)} }}${t}{{ else }}${n}{{ end }}`}const DR=`{{ and ${ca(lP)} .preset.customized }}`,OR=eS;function kR(e){return new Map([...kte(e),...jR(e)])}const AR=`${Zx}addable`;function jR(e){return new Map([[AR,{members:Object.keys(e.segments).filter(e=>!OR(e)),library:{groups:ZN.map(e=>({id:e,label:QN[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function MR(e,t,n){return n.segments[e]={template:t,when:uP,bg:pP},{kind:`segment`,name:e}}function NR(e,t,n){let r=`${Zx}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${M_}`}) (action "${r}" "✖") }}`}function PR(e){return`{{ if ${ca(lP)} }}${e}{{ end }}`}function FR(e,t){return e.reduce((e,t)=>`{{ if and ${ca(lP)} ${ca(t)} }}true{{ else }}${e}{{ end }}`,t)}function IR(e){return e.flatMap(e=>[...Zv(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function LR(e,t,n){return`${sP}${e}.${t}.${n}`}function RR(e,t,n,r){let i=qv(n),a=`${Zx}${e.presetIdent}`,o=cP(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=UM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:ea},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:iP,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=LR(e.presetIdent,i,r),l=`${sP}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:_y(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=tN($M(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 oa(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${_P}" }}`,ref:{variable:iP,key:iP,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const zR=`${Zx}label:`;function BR(e){if(e.startsWith(zR)){let t=e.slice(zR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function VR(e,t,n,r){let i=qv(e),a=HR(n,i,e,t,i),o=Object.fromEntries(fy.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...oa(a,r.ref,r.body,`drop`,FR([r.ref],`{{ ${wR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(fy.map(e=>[e,r.drafts[e]]))}}function HR(e,t,n,r,i){let a=`${zR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${aa(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function UR(e,t,n,r){let i=qv(e),a=n?[KR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=KR(r,o,i,`after`),c=NR(r,o,i),l=r.segments[e.name],u=RR(r,o,e,py(l)),d=PR(c),f=PR(u.term);return[...a.map(e=>MR(e.host,e.template,r.artifacts)),{...VR(e,l,r,u),lead:d,trail:f},{...t,when:ER(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},MR(s.host,s.template,r.artifacts)]}function WR(e){return s.join(s.basename(s.dirname(e)),s.basename(e))}function GR(e,t,n,r){let i=r.segments[e.name],a=qv(e);return[{kind:`segment`,name:HR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${WR(t.file)} ${t.entry}`),when:`{{ ${wR(r.presetIdent)} }}`},{...n,when:ER(r.presetIdent,`false`,e.when??`true`)}]}function KR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Zx}${i}.insert.${t}`,s=`${Zx}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:AR,anchor:n,relation:r};let c=VM(o),l=HM(s,o,void 0),u=GM(l),d=WM(l,c);return a.variables[l]={...fa(l,ea),within:[lP]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=pa(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ca({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${M_}`}) $m }}{{ end }}`}}function qR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!OR(e.name)&&e.insertedBy===void 0),i=e=>qR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Xv(o,i);if(OR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?UR(o,s,a===r,t):GR(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:FR(IR(n),ER(t.presetIdent,`true`,e.when))}}}function JR(e,t,n,r,i,a,o){let s=`${Zx}${t}.resetLayout`,c=`${Zx}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:DR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},YR(e,o)]}}function YR(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),YR(n,t)]}:{...e,children:[...e.children,t]}}function XR(e,t,n,r,i,a){let{node:o}=Fx(e,t),s={presetIdent:BM(t),rootKey:WN(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=qR(o,s);return n.variables[CR(s.presetIdent)]=TR(s.configured),JR(c,s.presetIdent,s.rootKey,n,r,i,a)}function ZR(e){let t={variables:{},actions:{},segments:{}},n=fP(`${Zx}help`,bP,[lP],t);t.variables[mR]=fa(mR,ea),t.actions[mR]=pa(mR,SR.member),t.segments[mR]={template:la(mR,...hR),when:uP};let r={kind:`segment`,name:mR},i=n;t.variables[yR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[gR]={do:[GI,aP]},t.segments[gR]={template:`{{ if ${xR} }}{{ action "${gR}" "✓ save" }}{{ else }}{{ action "${gR}" "✓ done" }}{{ end }}`,when:uP},t.actions[vR]={rewind:!0},t.actions[_R]={do:[vR,aP]},t.segments[_R]={template:`{{ action "${_R}" "↩ cancel" }}`,when:`{{ and ${ca(lP)} ${bR} }}`};let a=[{kind:`segment`,name:gR},{kind:`segment`,name:_R}],o={...e.presets},s=[];for(let n of Mx(e.presets)){let c=XR(e,n,t,a,r,i);s.push(c),o[n]={...Px(e.presets,n),root:c}}let c=zM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function QR(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function $R(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 ez(e,t,n){let r=Yv(e,new Set(n.map(Jv).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const tz=/^-?\d+$/;function nz(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 rz(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!tz.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 iz(e,t,n){return r=>r?tz.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 az(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=>!tz.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 oz(e){return e===`config`?`set-config`:`set-state`}function sz(e,t,n){return t.kind===`int`?rz(`menu page "${e}"`):t.kind===`range`?iz(t.min,t.max,`${n} stepper "${e}"`):nz(t.allowed,`${n} "${e}"`,oz(n))}function cz(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:az(e,n,t)}))}function lz(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 cz(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,sz(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 uz(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};lz(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=lz(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function dz(){return uz({},`config`,hz)}function fz(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:Hx(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:[QR({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[QR({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Hx(e.insertSegmentFrom,t).members.map(t=>QR({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function pz(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(WN(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function mz(e){let t=kR(e);return[...pz(e),...Object.values(e.actions).flatMap(e=>fz(e,t))]}function hz(e){return cz(mz(e),`config`)}const gz=ov(),_z=new Set(gz),vz=new Set(Ov),yz=e=>e?_z.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${gz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},bz=e=>e?vz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Ov.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},xz=new Set([`1`,`true`]),Sz=new Set([`0`,`false`]),Cz={endcaps:bz,theme:yz,"toolbar-expanded":e=>xz.has(e)?{ok:!0,value:`1`}:Sz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function wz(){return uz(Cz,`state`,Oz)}function Tz(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:Hx(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 Ez(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(Cz,e.key))}function Dz(e){let t=kR(e);return Ez(Object.values(e.actions).flatMap(e=>Tz(e,t)))}function Oz(e){return cz(Dz(e))}function kz(e){let t=wz(),n=dz();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 Az=`update.dismissed`,jz=`updateNotice`,Mz=nx.updateNotice.sessionKey;function Nz(){return kz({config:[{key:jz,allowed:[`false`]}],state:[{key:Mz,allowed:[`false`]},{key:Az,allowed:[]}]})}function Pz(e){try{return h.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Fz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:Rz(t.segments,Iz(t.segments,e.segments??{})),root:Tx(e.root??yx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:Rz(t.presets,Lz(t.presets,e.presets??{})),themeDefaults:Rz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Iz(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 Lz(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 Rz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const zz=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 Bz(e){let t=zz.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 Vz(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: ${ry.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Wz(e,`${t}.cache`,n.cache)}function Hz(e){return{required:!0,json:Gz(),parse:(t,n,r,i)=>Vz(t,n,i,e)??void 0}}const Uz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&qz(n)?{ttl:n}:Gy(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Y(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Gy(e,t,`cache.watch_file must be a path string, got ${Y(n)}`);let r=rb(`cache.watch_file`,n);return r===null?{watch_file:n}:Gy(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}:Gy(e,t,`cache.depends_on must be an array of variable-name strings, got ${Y(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Gy(e,t,`cache.key must be a non-empty template string, got ${Y(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Gy(e,t,`cache.never must be the literal boolean true, got ${Y(n)}`)}}};function Wz(e,t,n){return Ky(e,Uz,t,n)}function Gz(){return ub(Uz)}const Kz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function qz(e){return Kz.test(e)}const Jz=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 Yz(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 Xz(e){let t=Jz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Yz(t)}`}function Zz(e){let t=Jz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Yz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const Qz=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`]]),$z=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 eB(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 tB(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`?$z.get(e.field):void 0;if(n===void 0){let e=[...$z.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 ${eB(n.declare)} under a name of your own`}const nB=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 rB(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`?nB.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 ${eB(n.declare)} under a name of your own`}function iB(e,t,n){if(n===void 0)return{};if(!Hv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${zy(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=qy(e,EB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function aB(){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 ${zy(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function oB(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Fy(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const sB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Gy(e,t,`parse.text must be the literal boolean true, got ${Y(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?cB(e,t,n):Gy(e,t,`parse.regex must be a pattern string, got ${Y(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Gy(e,t,`parse.json must be the literal boolean true, got ${Y(n)}`)}}};function cB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Gy(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Gy(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function lB(){return{required:!1,json:ub(sB),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:Ky(e,sB,`${t}.parse`,r.parse)??void 0)}}function uB(){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)=>Hv(r.parse)&&`json`in r.parse?dB(e,t,r.default):Iy(e,t,r,`default`)}}function dB(e,t,n){if(n!==void 0)return fB(n)?n:Gy(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Y(n)}`)??void 0}function fB(e){return e!==null&&UC(e)}const pB={value:aB(),default:Zy()};function mB(){let e=nb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:Qz.get(a);return o===void 0?a:Gy(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const hB={path:mB(),type:ab([`string`,`number`,`boolean`]),default:oB()},gB={path:ib(),readMode:ab([`whole`,`first-line`]),parse:lB(),cache:Hz(`file`),default:uB()},_B={command:nb(),parse:lB(),cache:Hz(`shell`),default:uB()};function vB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const yB={template:nb(),type:ab([`string`,`number`,`boolean`]),default:oB()},bB=vB(`a template variable recomputes whenever a variable it reads changes`),xB={layout:nb(),default:Zy()},SB=vB(`a time variable reads the instant its render is drawn at`),CB={key:nb(),default:Zy()},wB=`kind`;function TB(e,t,n={}){return{...Jy(wB,e,t),parse:(r,i,a)=>{Vy(r,n,i,a);let o=Hy(r,t,i,a);return o===null?null:{kind:e,...o}}}}const EB={tag:wB,noun:`source kind`,memberNoun:`variable`,arms:{literal:TB(`literal`,pB),input:TB(`input`,hB),file:TB(`file`,gB),shell:TB(`shell`,_B),template:TB(`template`,yB,bB),time:TB(`time`,xB,SB),state:TB(`state`,CB)},retired:{git:tB,env:rB}};function DB(){return lb(EB)}function OB(){return{type:`object`,additionalProperties:DB()}}const kB=/^[A-Za-z_][A-Za-z0-9_]*$/,AB={pattern:kB.source},jB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},MB={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`,...AB}}}]},default:jB}},NB=[`label`,`domain`,`default`],PB=[`min`,`max`,`step`,`atLeast`];function FB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function IB(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 FB(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 FB(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?FB(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(Hv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!PB.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}}:FB(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 FB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Y(n)}`)}function LB(e,t,n){if(!Hv(n))return FB(e,t,`${t} must be { label, domain, default }, got ${zy(n)}`);for(let r of Object.keys(n))NB.includes(r)||FB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${NB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||FB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Y(r)}`);let a=IB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!RB(n.default)||!gy(o,n.default)?FB(e,`${t}.default`,`default must be ${by(o)}, got ${Y(n.default)}`):o}function RB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const zB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${uy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function BB(e){return fy.includes(e)}function VB(){return{required:!1,json:{type:`object`,propertyNames:{...AB,not:{enum:[...fy]}},additionalProperties:MB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Hv(i))return FB(e,a,`${a} must be an object of name → { label, domain, default }, got ${zy(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!kB.test(t)){FB(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(BB(t)){FB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${zB[t]}`);continue}let r=LB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const HB=$x.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function UB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${HB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!eS(i)?i:FB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${$x.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Y(i)}`)}}}function WB(){return{required:!1,json:{type:`object`,propertyNames:AB,additionalProperties:jB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Hv(i))return FB(e,a,`a placement's "settings" must be an object of setting name → value, got ${zy(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))RB(n)?o[t]=n:FB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${zy(n)}`);return o}}}function GB(e){return new Set(Object.keys(e.segments).filter(e=>!eS(e)))}function KB(e,t,n){if(t===void 0)return{};if(!Hv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${zy(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=By(e,n.has(i)?nV:tV,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function qB(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 ${zy(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 ${zy(i)}`,line:J(e.source,[...t.split(`.`),n])})}const JB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function YB(){return{required:!0,json:JB,parse:(e,t,n,r)=>r[n]===void 0?Gy(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${Bz(t.slice(9))}`)??void 0:qB(e,t,n,r)}}function XB(){return{required:!1,json:JB,parse:(e,t,n,r)=>r[n]===void 0?void 0:qB(e,t,n,r)}}function ZB(){return{required:!1,json:{type:`object`,additionalProperties:JB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Hv(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${zy(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=qB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function QB(){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 ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function $B(){return{required:!1,json:OB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return iB(e,`${t}.${n}`,i)}}}const eV={template:YB(),description:Zy(),group:ab(XN),width:QB(),justify:ab(xy),truncate:ab(Sy),bg:Zy(),fg:Zy(),when:Zy(),palette:tb(),vars:$B(),settings:VB(),missingData:ab(sy),partials:ZB()},tV={noun:`segment key`,fields:eV},nV={noun:`segment key`,fields:{...eV,template:XB()}};function rV(e,t){if(t===void 0)return{};if(!Hv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${zy(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 ${Y(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function iV(e,t,n){if(t===void 0)return{};if(!Hv(t))return Z(e,`actions`,`actions must be an object, got ${zy(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=aV(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function aV(e,t,n,r){if(!Hv(n))return Z(e,t,`${t} must be an action object, got ${zy(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=Wx.filter(e=>e in n);return i.length===1?sV(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${Wx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function oV(e){return e===`<default>`?{dir:null}:s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const sV=e=>({set:(e,t,n)=>UV(e,t,n,`set`,zV),persist:(e,t,n)=>UV(e,t,n,`persist`,BV),copy:cV(`copy`),open:cV(`open`),reset:lV,undo:dV(`undo`),redo:dV(`redo`),back:dV(`back`),rewind:dV(`rewind`),save:dV(`save`),preset:fV,themeDefault:pV,doctor:hV,slash:gV,run:yV(e),do:bV});function cV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Py(t,n,r,e);return i===null?null:{[e]:i}}}function lV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=xV(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 uV={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 dV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${uV[e]}), got ${Y(r[e])}`),null)}}function fV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${Y(r)}`),null;if(r===`save`)return{preset:`save`};let a=Py(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function pV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Y(n.themeDefault)}`),null)}const mV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function hV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(mV,r),a=i?mV[r]:[...new Set(Object.values(mV).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(mV).map(e=>`"${e}"`).join(`, `)}, got ${Y(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?qF:KF;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Y(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return SF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${SF.map(e=>`"${e}"`).join(` or `)}, got ${Y(c)}`),null)}function gV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=xI(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const _V=[`run`,`env`,`refreshes`],vV=/^[A-Za-z_][A-Za-z0-9_]*$/;function yV(e){return(t,n,r)=>{for(let e of Object.keys(r))_V.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${_V.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${Y(a)}`);let o=r.env??{};(!Hv(o)||Object.entries(o).some(([e,t])=>!vV.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${Y(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${Y(s)}`),`dir`in e||Z(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}}}vV.source;function bV(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${Y(r)}`),null):{do:r}}function xV(e,t,n,r,i,a){let o=Py(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const SV={set:`the SessionState key to write`,persist:`the config globals field to write`};function CV(e,t,n,r){let i=SV[r],a=xV(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 wV(e){return e===`set`?`set-state`:`set-config`}const TV={to:WV(`set`)},EV={to:WV(`persist`)},DV={from:GV(`set`)},OV={from:GV(`persist`)},kV={min:XV(),max:XV(),by:XV()},AV={int:qV()},jV={cycle:KV(`set`)},MV={cycle:KV(`persist`)},NV={removeSegment:JV(`removeSegment`)},PV={insertSegment:JV(`insertSegment`),anchor:JV(`anchor`),relation:YV()},FV={insertSegmentFrom:GV(`persist`),anchor:JV(`anchor`),relation:YV()},IV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},LV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function RV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Hy(e,t,n,r),c=ob(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?Xy(s,...n):s}}const zV=[RV(`set`,TV),RV(`set`,DV),RV(`set`,kV,[IV,LV]),RV(`set`,AV),RV(`set`,jV)],BV=[RV(`persist`,EV),RV(`persist`,OV),RV(`persist`,kV,[IV,LV]),RV(`persist`,MV),RV(`persist`,NV),RV(`persist`,PV,[],[`insertSegment`]),RV(`persist`,FV,[],[`insertSegmentFrom`])];function VV(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 HV(e){let t=VV(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 UV(e,t,n,r,i){let a=CV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${HV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function WV(e){let t=wV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>xV(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 GV(e){let t=wV(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Y(o)}`)}}}function KV(e){let t=wV(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${zy(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function qV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Y(r[n])}`);return}return!0}}}function JV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Py(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function YV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${Y(i)}`);return}return i}}}function XV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${Y(i)}`);return}return i}}}function ZV(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const QV=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),$V=`plugin.json5`,eH=/^[a-z][a-z0-9_]*$/;function tH(e,t){let n=s.basename(s.dirname(e));return eH.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function nH(e){return`${e}.data`}function rH(e){return`${e}.json`}function iH(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:aH(e)}}}function aH(e){return e instanceof Cy?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 oH(e,t,n,r){return e.map(e=>tH(CP(s.dirname(t),e,r),n))}function sH(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:eC(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(s.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${$V}, and the folder's name is the plugin's: move this file to <dir>/<name>/${$V} and list that`;return c(t,o===void 0?e.config:lH(cH(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return c(`its folder "${s.basename(s.dirname(a))}" is not a plugin name (one matching ${eH}: 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=cH(e.config,o),d=iH(()=>{let i=h.readFileSync(a,`utf-8`),s=Fz(hH(a,n,{source:i,json:ya.default.parse(i)},t),u);return AH(a,o,s),r(s,o,u!==e.config),s});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,lH(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function cH(e,t){let n=tC(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 lH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:ZV(n),definition:n.path}}}}function uH(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})=>tC(t)(e))}function dH(e,t){let n=uH(e.config),r=[...e.rendering.keys()].map(tC),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=rC(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:ZV(e)})):[{definition:a.definition,notice:a.notice}]}}function fH(e,t,n){let r=Mx(e.presets).flatMap(t=>[...Zv(Fx(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,pH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=uH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...yH.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=>wC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...MC(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 pH(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,mH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function mH(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 hH(e,t,{source:n,json:r},{checkout:i,home:a}){let o=eC(t),c=[],l=()=>{throw new Cy(e,c)};if(!Hv(r))return c.push({path:``,message:`a plugin definition must be an object, got ${zy(r)}`}),l();for(let t of Object.keys(r))QV.has(t)||c.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${s.basename(s.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...QV].join(`, `)}`});let u=r.data===void 0?void 0:NH(r.data,e,i,a,c),d=r.sources===void 0?{}:kH(r.sources,e,c);if(c.length>0)return l();let f={source:n,issues:c,allowedPalettes:new Set(ov()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:iB(f,`data`,{[nH(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=iB(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 (.${nH(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 g={variables:{...p,...SH(o,d),...SH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,wH(o,t)])))},segments:SH(o,TH(o,KB(f,r.segments,new Set))),helpers:SH(o,rV(f,r.helpers)),actions:SH(o,EH(o,iV(f,r.actions,{dir:h.realpathSync(s.dirname(e))})))};c.push(...bH(g,t));let _=gH(o,g);for(let[e,t]of xH(_))try{$N.parse(t)}catch(t){c.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return c.length>0&&l(),_}function gH(e,t){let n=t=>PC(t,nC,e),r=t=>tC(`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=>_H(ay(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(yH.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=>_H(ay(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>vH(qx(e,n),r))}}function _H(e,t){return iy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function vH(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 yH=[`template`,`bg`,`fg`,`when`];function bH(e,t){let n=e.helpers??{},r=$S.filter(e=>e!==t.scope).map(e=>({scope:e,ns:eC({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>tC(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 ${eC(t)}: a plugin names itself without its scope — write ${s}${nC}${n.slice(o.ns.length)}`})},o=[...[...xH(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 bC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of wC(t,n))i===null&&a(e,r,!1);for(let n of MC(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))vH(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(iy(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*xH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of oy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of yH){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 oy(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 Kx(n))yield[`actions.${t}.${e}`,r]}function SH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function CH(e,t){return`${e}.${t}`}function wH(e,t){return t.kind===`state`?{...t,key:CH(e,t.key)}:t}function TH(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,wH(e,n)]))}]))}function EH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:CH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>CH(e,t))}:n]))}const DH=eH,OH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function kH(e,t,n){if(!Hv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${zy(e)}`}),{};let r=s.join(h.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(OH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!DH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${DH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=MH(o,OH,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 AH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=jH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=tC(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 Cy(e,a)}function jH(e){return s.join(e.storage,rH(`<session id>`))}function MH(e,t,n){return!Hv(t)||!Hv(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)?MH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function NH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return CP(s.dirname(t),e,r);if(Hv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){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 s.resolve(n.root,t)}if(Hv(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 PH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),FH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:s.join(t,IH),scope:`repo`}]]}function FH(e){return s.join(e.dataHome,`cc-candybar`,`plugins`)}const IH=s.join(`.cc-candybar`,`plugins`);function LH(e,t){let n=PH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=RH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=tH(s.join(e,i,$V),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:s.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${$V}: move this file to ${s.join(e,`<name>`,$V)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function RH(e){try{let t=h.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()||zH(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 zH(e,t){if(!t.isSymbolicLink())return!1;try{return h.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}const BH=[`approved`,`declined`];function VH(e){return e.link.kind===`linked`?e.link.main:e.dir}const HH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function UH(e,t){let n=VH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=HH(e.value,n),i=HH(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 WH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...UH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&UH(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 GH(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 KH(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(!BH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${BH.join(` or `)}`};return{kind:`ok`,value:e}}function qH(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 JH(e){let t=qH(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 YH=[`json5`,`json`];function XH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?YH.map(e=>s.join(t,`${ZH}.${e}`)):[],...YH.map(e=>s.join(i,`${ZH}.${e}`)),...YH.map(t=>`${QH(e)}.${t}`)])]}const ZH=`.cc-candybar`;function QH(e){return s.join(e.configDir,`config`)}function $H(e){return{path:e,scope:`plugins`}}function eU(e,t,n,r,i){let a=[],o=new Map;for(let t of XH(e,n,r,i)){let n=Pz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=h.realpathSync.native(s.dirname(t)),c=s.join(r,s.basename(t).replace(/\.(json5|json)$/,``));o.has(c)||o.set(c,{file:t,repo:i!==void 0||tU(e,t)?null:{dir:r,link:dc(r)}})}let c=[...o.values()],l=WH(t,c.flatMap(e=>e.repo===null?[]:[e.repo]),nU(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:rU(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 tU(e,t){return YH.some(n=>t===`${QH(e)}.${n}`)}function nU(e){if(e===void 0||Pz(e)!==`present`)return null;let t=RH(s.join(e,IH)),n=h.realpathSync.native(e);return{dir:n,link:dc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function rU(e,t){return t.find(t=>tU(e,t.path))?.path??`${QH(e)}.${YH[0]}`}function iU(e,t,n,r,i){let a=eU(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 aU(e){return oU(e).join(`
|
|
194
|
+
`)||null}function oU(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 sU(e,t,n){let r=XH(e,t,n).filter(e=>Pz(e)===`present`),i=new Map;for(let e of r){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),r=s.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 cU(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=h.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&&dr(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const lU={level:`error`,glyph:`⚠`,colors:RP},uU={level:`warning`,glyph:`⚠`,colors:zP},dU={level:`warning`,glyph:`⬆`,colors:zP},fU={level:`warning`,glyph:`🔒`,colors:zP},pU={level:`warning`,glyph:`🧪`,colors:zP};function mU(e,t){return{text:VP(e),link:t}}function hU(e,t,n,r,i,a){let o=new Set,s=(e,t)=>{let n=gU(e,t);for(let e of n)o.add(e);return n},c=[...r.flatMap(e=>s(e,lU)),...i,...a.flatMap(e=>s(e,uU))],l=_U(c);return c.map((r,i)=>o.has(r)?{...r,lines:[[mU(r.lines[0][0].text,vU(e,t,n,l[i],i+1))],...r.lines.slice(1)]}:r)}function gU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>mU(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 _U(e){return SU(e).map(e=>String(e*bU+1))}function vU(e,t,n,r,i){return HS(e,[{verb:jS,args:[t,n,r]}],`copy diagnostic ${i}`)}function yU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const bU=4096;function xU(e){let t=ce(`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 SU(e){let t=new Map;return e.map(e=>{let n=xU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function CU(e,t,n){return String(SU(e)[t]*bU+n+1)}const wU={error:RP,warning:zP};function TU(e){let t=yU(e),n=e.length,r=wU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:CU(e,0,0)}}function EU(e,t){let n=Number(e)-1,r=SU(t).indexOf(Math.floor(n/bU));return e===null||r===-1?null:{index:r+1,page:n%bU}}function DU(e,t){return Math.min(20,e??20,...t)}function OU(e,t,n,r,i,a){let{index:o}=t,s=e[o-1],c=jU(a),l=PU(s,c,[]),u=new W({bgcolor:s.severity.colors.bg,color:s.severity.colors.fg}),d=(e,t)=>MU(e,t===null?u:u.withLink(t)),f=(t,i)=>i===null?d(` `,null):d(t,AU(n,r,CU(e,i.index-1,i.page),`show diagnostic ${i.index} of ${e.length} page ${i.page+1}`)),p=(t,a)=>{let s=a>0?{index:o,page:a-1}:o>1?{index:o-1,page:0}:null,l=a<t-1?{index:o,page:a+1}:o<e.length?{index:o+1,page:0}:null,u=e.length>1||t>1,p=t>1?`[${o}/${e.length} ${a+1}/${t}]`:`[${o}/${e.length}]`;return NU([d(`✕`,AU(n,r,`0`)),...u?[f(`‹`,s)]:[],d(p,null),...u?[f(`›`,l)]:[],d(`⧉ copy`,vU(n,r,i,CU(e,o-1,0),o))],c)},m=1;for(;;){let e=Math.max(1,a.rows-m),n=Math.min(bU,Math.ceil(l.length/e)),r=Math.min(t.page,n-1),i=p(n,r);if(i.length>m){m=i.length;continue}let o=l.slice(r*e,(r+1)*e),s=l.length-(r+1)*e,u=r===n-1&&s>0?[...o.slice(0,-1),...NU([d(`… ${s+1} more rows: ⧉ copy has them all`,null)],{...c,wrap:!1})]:o;return[...i,...u]}}function kU(e,t,n,r,i){let{label:a,fg:o,bg:s,open:c}=TU(t),l=a===``?[]:[MU(a,new W({bgcolor:s,color:o}).withLink(AU(n,r,c)))];return PU(e,jU(i),l)}function AU(e,t,n,r){return HS(e,[{verb:sS,args:[t,iS,n]}],r)}function jU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const MU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),NU=(e,t)=>sF(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function PU(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=Kc(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=MU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Zc(e,a)).map(t=>MU(t,i(e.link)))),u=s===0?n:[];return NU([c,...l,...u],t)})}const FU=`repo-configs.json`;function IU(e){return s.join(e,`repo-configs`)}function LU(e){return s.join(IU(e),FU)}const RU=e=>{let t=cU(IU(e),FU,{},KH),n=cU(e,FU,{},KH),r=()=>h.existsSync(LU(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 zU(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:Pz(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&VH({dir:e,link:dc(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]:[])},GH(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function BU(e,t,n){return{sessionId:e,action:AS,declaration:t,evaluated:n}}function VU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=BH.map(r=>mU(`[${r===`approved`?`approve`:`decline`}]`,HS(n.to,[{verb:AS,args:[t,e,r,n.signer.sign(BU(t,e,r))]}]))),a=[mU(r,null),...i];return{severity:fU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function HU(e){return Math.max(1,e-2)}function UU(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function WU(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const GU={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},KU={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function qU(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const JU={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function YU(e){return Object.keys(JU).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${JU[t]}: ${n.reason}`]:[]})}function XU(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(ZU(e,t),`read`)}function ZU(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??QU(t.stderr)].filter(Boolean).join(`, `)}`}function QU(e){return e.trim().split(`
|
|
195
|
+
`,1)[0]??``}function $U(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function eW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const tW={github:`gh`,gitlab:`glab`};function nW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const rW=/^[A-Za-z]:[\\/]/;function iW(e){let t=e.trim();if(rW.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 aW(e){return iW(e)?.host||null}function oW(e){let t=aW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const sW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function cW(e){let t=XU(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?lW(t.value):[]}}function lW(e){let t=new Map;for(let n of e.split(`
|
|
196
|
+
`)){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 uW(e){return e.urls.find(e=>hW(e)!==null)??e.urls[0]??null}function dW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function fW(e){let t=dW(e);return t?uW(t):null}function pW(e){let t=dW(e);return t?t.urls.find(e=>oW(e)!==null)??uW(t):null}function mW(e){let t=(iW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function hW(e){let t=iW(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 gW(e){let t=fW(e);return t===null?null:hW(t)}function _W(e,t,n,r){return t.ok?r(t.stdout):nW(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??QU(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function vW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yW(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
197
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function bW(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!vW(t))return L(`gh pr view: JSON is not an object`,`parse`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`,`parse`);let o=qU(`gh pr view`,GU,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function xW(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!vW(t))return L(`glab mr view: JSON is not an object`,`parse`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`,`parse`);let o=qU(`glab mr view`,KU,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function SW(e){try{let t=h.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var CW=class{constructor(e){this.launcher=e}isGitRepo(e){return tc(e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=nc(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`,`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=$U(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=$U(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=$U(s,gW)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){return ao(sc(e),s.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return h.existsSync(s.join(t,`MERGE_HEAD`))?F(`MERGE`):h.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):h.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):h.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):h.existsSync(s.join(t,`rebase-merge`))||h.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async getNearestTagAsync(e){return eW(XU(`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=eW(XU(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`,`parse`):F(r)}resolveCommonGitDir(e){return ao(cc(e),e)}getStashCount(e){let t=s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=h.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return F(r?r.split(`
|
|
198
|
+
`).length:0)}async getRemotesAsync(e){let t=SW(s.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 cW(await this.execGitAsync(sW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=fW(e);return(n===null?null:mW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=pW(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=oW(t);return n===`github`?_W(`gh pr view`,await this.execForgeAsync(tW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,bW):n===`gitlab`?_W(`glab mr view`,await this.execForgeAsync(tW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,xW):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(h.existsSync(t)&&h.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){Pe(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=XU(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(yW(t.value)):t}};const wW=`#/definitions/LayoutNode`,TW={kind:`container`,direction:`vertical`,children:[]};function EW(e){return{required:!0,json:{const:e},parse:()=>e}}function DW(){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 ${Y(i)}`,line:J(e.source,[`root`])}),``)}}}function OW(){return{required:!0,json:{enum:[...Gv]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Gv.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Gv.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function kW(e){return{required:!0,json:{type:`array`,items:{$ref:wW}},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 ${zy(a)}`,line:J(t.source,[`root`])}),[])}}}const AW={noun:`layout-node key`,fields:{kind:EW(`segment`),name:DW(),when:Zy(),id:UB(),settings:WB()}},jW=()=>ab(m_),MW={noun:`layout-node key`,fields:{kind:EW(`container`),direction:OW(),children:kW(Yy(()=>LW)),when:Zy(),distribution:jW()}};function NW(){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 ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])}),``)}}}const PW={noun:`layout-node key`,fields:{seg:NW(),when:Zy(),id:UB(),settings:WB()}},FW={noun:`layout-node key`,fields:{h:kW(Yy(()=>LW)),when:Zy(),distribution:jW()}},IW={noun:`layout-node key`,fields:{v:kW(Yy(()=>LW)),when:Zy(),distribution:jW()}},LW=(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`])}),TW):{kind:`segment`,name:n};if(!Hv(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 ${zy(n)}`,line:J(e.source,[`root`])}),TW;if(n.kind===`container`)return By(e,MW,t,n)??TW;if(n.kind===`segment`)return By(e,AW,t,n)??TW;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
203
199
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
204
|
-
New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),dJ;if(n.kind===`group`){let r=Hy(e,MJ,t,n);return r===null?dJ:(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}),PJ(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`])}),dJ}if(a){let r=Hy(e,bJ,t,n);return r===null?dJ:{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=Hy(e,xJ,t,n);return r===null?dJ:{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=Hy(e,SJ,t,n);return r===null?dJ:{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`])}),dJ};function wJ(){return{required:!0,json:{type:`object`,propertyNames:{pattern:xx.source},additionalProperties:{$ref:uJ}},parse:(e,t,n,r)=>{let i=r[n];if(!Wv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Vy(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]=CJ(e,`${t}.${n}.${r}`,o)}return a}}}const TJ={noun:`root key`,fields:{rows:wJ(),when:$y(),distribution:_J()}};function EJ(e,t,n){return Wv(n)&&`rows`in n?Hy(e,TJ,t,n)??{rows:{}}:CJ(e,t,n)}const DJ={noun:`insert key`,fields:{seg:yJ(),id:qB(),before:$y(),after:$y()}};function OJ(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Hy(e,DJ,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(rS(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 rS(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 ${Vy(t)}`,line:J(e.source,[`insert`])}),[])}function kJ(){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 "${ea}", got ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}function AJ(){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 ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}}function jJ(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Iy(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 MJ={noun:`layout-node key`,fields:{kind:fJ(`group`),name:kJ(),label:jJ(),open:eb(),direction:sb(qv),key:AJ(),bg:$y(),fg:$y(),when:$y(),distribution:_J(),children:hJ(Zy(()=>CJ))}};function NJ(e){return e.key??`groups.`+e.name}function PJ(e){let t=Zx+e.name;return oa(t,{variable:t,key:NJ(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function FJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function IJ(e,t){iP(e,t,Zx,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&FJ(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}.`)&&NJ(t)===NJ(r)&&FJ(e,t.path,`group "${t.name}" shares key "${NJ(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=NJ(t);if(i.has(n)||i.set(n,ea),t.open===!0){let r=i.get(n);r!==`closed`&&FJ(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=Zx+e.name,r=NJ(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=fa(r,i.get(r)),o[t]=pa(r,e.name),s[t]={template:la(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 LJ=`menu`,RJ=`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`,zJ=e=>e.kind===`call`&&e.name===`dict`,BJ=e=>e.kind===`literal`&&typeof e.value!=`object`,VJ=e=>ra(``,e,2)===void 0;function HJ(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&&zJ(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(zJ))return t(`whose options (dict …) is not its last argument — ${RJ}`);if(i!==void 0&&a===void 0&&!BJ(i)&&VJ(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=ra(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${RJ}`);let c=a===void 0?{}:XD(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=QM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=rP(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 "${KM(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 UJ(e){let t=aE({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===LJ).map(HJ)}catch{return`parse-failed`}}function WJ(e,t){let n=UJ(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:GM(t,e.apply,e.options.key),member:WM(e.apply)}]:[])}function GJ(e){let t=aE({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(LJ)}catch{return!1}}function KJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function qJ(e,t){iP(e,t,Qx,`{{ menu }} helpers`),iP(e,t,$x,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))GJ(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`&&GJ(i)&&KJ(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??{}))GJ(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 $v(Ex(t.root)))typeof n.when==`string`&&GJ(n.when)&&KJ(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||!GJ(r))continue;let n=UJ(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:JJ(r.apply);n!==void 0&&KJ(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function JJ(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 "${ea}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function YJ(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 Fx(e.presets)){let a=new Map,s=new Map;for(let c of $v(Rx(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,UJ(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Yv(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||JJ(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=WM(i),f=GM(u,i,l.key),p=JM(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=qM(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]=pa(f,d),n[f]=fa(f,ea),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 XJ(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const ZJ={noun:`style key`,fields:{hueShift:nb(),chromaScale:nb({min:0}),lightnessScale:nb(),lightnessShift:nb()}};function QJ(e,t){if(!Wv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Vy(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(Mv(r)){e.issues.push({path:`styles.${r}`,message:XJ(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=Hy(e,ZJ,`styles.${r}`,i);t!==null&&(n[r]={...cu,...t})}return n}const $J={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:EJ(e,`${t}.${n}`,r[n])},globals:{required:!1,json:FN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:PN(e,`${t}.${n}`,r[n])}}};function eY(e,t){if(!Wv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Vy(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=Hy(e,$J,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function tY(e,t){let n=[...t].map(([e,t])=>[iC(e),t]);return t=>{if(nR(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=oC(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function nY(e){return e.kind===`plugin`||e.kind===`missing`}function rY(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>Cx(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 $v(e))t.kind===`segment`&&i(Yv(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 iY(e){let t=0,n=tY(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)?[Qv(e,i)]:[],o=e=>a(e)[0]??aY,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>Cx(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 aY={kind:`container`,direction:`horizontal`,children:[]},oY={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 sY(e,t){let n=new Map;for(let e of Object.keys(t)){let t=UM(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 cY(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 Dx(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const lY=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${rC(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${uY(rC(r.definition),n)}${dY(t,n)}`:`${e} entry "${t}" does not match any declared segment${dY(t,n)}`;function uY(e,t){let n=Object.keys(t).filter(iC(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 dY(e,t){return Wz(e)+sC(e,e=>Object.hasOwn(t,e))}function fY(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||mv(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Mv(r)?XJ(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`])}),sY(e,t.presets);let a=HC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(hY)||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)=>{aR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iS}" ${aR(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}),oR(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iS}" 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:oY[a](n),line:i});let o=new Map;for(let e of $v(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Yv(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=Zv(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`||Jv[e.direction]===`cell`);return Jv[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Jv[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,ey(t,n)]):e.opens===void 0?[]:[[e.opens.body,ty(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=Ex(n),s=Cx(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:oY[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of Dx(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(jY(e,`${s}.when`,o.when,a,{line:n}),kY(e,`${s}.when`,o.when,n),AY(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(nR(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${iS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${iS}"`,line:n});continue}let c=r(o.name);nY(c)&&(d.add(o.name),e.unplaced.push({path:s,message:lY(i,o.name,t.segments,c),line:n})),CY(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`,Tx(t.root)]]);for(let e of Fx(t.presets)){let{node:n,path:r}=Rx(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 ny(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);nY(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:lY(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}zY(e,t,a,()=>!0)}const pY=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function mY(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!Fx(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Fx(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(`, `)})${Wz(i)}`,line:c})},p=new Set(Xv(Rx(t,a).node)),m=(r,i)=>{!Uz.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${Wz(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 hY=`settings.`;function gY(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>hY+e)])}}function _Y(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=bY(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of _y(n,yY(n)))i(e,`the defaults do not stand together: ${t}`)}function vY(e){return bY(e).length>0||_y(e,yY(e)).length>0}function yY(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function bY(e){let t=t=>gy(xY(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||gy(xY(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${SY(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 xY(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function SY(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&gy(n)!==void 0).map(([e])=>e)}function CY(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=hy(a),s=`${r}: placement "${Yv(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(`, `)})`:vy(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?av(a):``}, but it must be ${Sy(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])=>vy(o[e],t))||vY(o)))for(let{message:t}of _y(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function wY(e,t,n,r,i){for(let[a,o]of cy(n))jY(e,`${t}.${a}`,o,r,{segCtx:i})}function TY(e,t,n,r,i){if(!(!oy(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 EY=`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 DY(e,t,n,r){if(!oy(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=iq(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${EY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=eq(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}: ${EY}`,line:i(`depends_on`)})})}}function OY(e,t){let n=new Map(zC(t)),r=XK(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=pv.find(e=>zM[e]===n||zM[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${zM[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=JK(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 nq(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 kY(e,t,n,r){try{nP.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function AY(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 DC(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){NY(e,u,`Template references unknown action "${c}"${r}`,MY(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function jY(e,t,n,r,i){let a=(n,r)=>{if(r!==null){NY(e,r,n,MY(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 CC(n,r.helpers)){if(VC(e,r))continue;if(e.startsWith(hY)){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}")`:tB(e)}`,t)}for(let{literal:e,via:t}of OC(n,r.helpers))a(`Template spells a link in a grammar older than names, which names no renderer: "${e}". Bind an action instead ({{ action "name" … }}): its link names the renderer that draws it`,t)}function MY(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function NY(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 PY(e,t,n,r,i){let a=n.set,o=vN(ax[r].configKey),s=`${a} takes ${tN(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=LY(n,i);if(c===IY){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=>!eN(o,e.value,i));if(l.length!==0){if(a===ax.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Mv(e.value)))){let r=ax.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:XJ(`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<=FY?r.join(`, `):`${r.slice(0,FY).join(`, `)} and ${r.length-FY} 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 FY=3,IY=Symbol(`any integer`);function LY(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?Gx(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)}]:IY}function RY(e,t){return Object.entries(e).filter(([e])=>t(e))}function zY(e,t,n,r){let i=NR(t),a=Wx(i);for(let[n,o]of RY(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 ${Kx(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;vte.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=fx.get(o.set);s!==void 0&&PY(e,n,o,s,i)}for(let[n,i]of RY(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&&Ote(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 RY(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 RY(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=ZN(r);if(o===null){let t=zN(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=pY.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`){mY(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Fx(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: ${Fx(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${av(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(`, `)})${Wz(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 RY(t.variables,r)){wY(e,`variables.${i}`,a,n);let t=eB(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of RY(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))wY(e,`segments.${i}.vars.${t}`,r,n,i);let r=hy(a);if(_Y(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=gY({...n,helpers:o},r);for(let n of CH){let c=a[n];typeof c==`string`&&(jY(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),AY(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of RY(t.variables,r))TY(e,`variables.${i}`,a,n),DY(e,`variables.${i}`,a,t);OY(e,t);for(let[i,a]of RY(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))TY(e,`segments.${i}.vars.${r}`,o,n,i),DY(e,`segments.${i}.vars.${r}`,o,t)}function BY(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=VY(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 VY(e){let t=new Map,n=new Map,r=XK(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 HY(e,t,n){let r=new Map([...RC(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 UY(e){return{...QY,config:zz(QY.raw,e)}}function WY(e,t,n,r,i){let a=aX(e,t,i,(t,a)=>{let o=dH(uH(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>XY(t,n,r,e,i)),s=hH(o,r.beneath.dropped);return{inherited:new Set([...YB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=gH(zz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(tH)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const GY=new WeakMap;function KY(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,JY(e.path)])]),a=GY.get(n)??new Map;GY.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=dH(e,t,{config:n,rendering:new Map},(e,t,n)=>XY(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function qY(e,t,n,r){return dH(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>XY(e,t,n,`<plugin install>`,void 0)).dropped}function JY(e){try{let t=h.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function YY(e,t,n,r,i,a=e=>h.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:rc(i.cwd),home:e.homeDir},c=VH(e,s.repo),l=KY(c.definitions,s,n,o),u={...l,dropped:[...l.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let{path:e,scope:n}of t){let t=f.at(-1)?.plugins,i=WY(e,a(e),f.at(-1)?.config??d,{...s,scope:n,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??u.rendering}},o);r.warned(i.warnings),f.push({...i,path:e})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),g=u.dropped.filter(m),_=u.dropped.filter(e=>!m(e));r.warned(g.map(tH));let v=f.at(-1)?.plugins.rendering??u.rendering,y={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:g,unreached:_,reached:p,rendering:v},b=f.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:f,base:d,installed:y,...x($Y(UY(d),v,`<default>`,o))};try{return{layers:f,base:d,installed:y,...x($Y(b,v,b.path,o,f.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of f.slice(0,-1).entries())$Y(t,t.plugins.rendering,t.path,o,f.slice(0,e).reverse());throw e}}function XY(e,t,n,r,i){if(n){$Y(ZY(e),new Map,r,i);return}let a=iC(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(zY(s,e,HC(e),a),BY(s,e,a),HY(s,e,{checked:a,authored:a}),o.length>0)throw new Ty(r,o)}function ZY(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const QY={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function $Y(e,t,n=`<config>`,r=new Set(cv()),i=[]){let a=tY(e.config.segments,t),o=tX({...e,path:n},i,a),s=(t,s)=>{let c=Tte(e.config,t,o.authored);return eX(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof Ty)||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 Ty))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,zx(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function eX({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 Ty(n,[...l,...u.unplaced,...u.inherited],c)};fY(u,a,e,o),BY(u,a),d();let f=rX(n,a.segments,u,o,i,s),p=YJ(iY(a),l);d();let m=tz(_R(p)),h=new Set([...RC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return HY(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function tX(e,t,n){let r=[...t].reverse().concat(e),i=rY(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>nY(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=Oy(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:lY(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function nX(e){if(e.length>0)throw new Dy(e)}function rX(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=cY(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:lY(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Ey(e,t))}function iX(e,t,n=new Set(cv()),r=oX){return aX(e,t,n,()=>({inherited:r,layer:null})).raw}function aX(e,t,n,r){let i=sX(e,t),a=Py(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(cv()),groups:[],unplaced:[],inherited:[]};if(!Wv(i))throw new Ty(e,[{path:``,message:`Config root must be an object, got ${Vy(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:uX({...c,issues:[]},i.plugins)??[],Wv(i.segments)?Object.keys(i.segments):[]),d=cX(c,i,l,uV(e),e);if(s.length>0)throw new Ty(e,s,o);return{raw:d,warnings:o,layer:u}}const oX=new Set;function sX(e,t){try{return ya.default.parse(t)}catch(t){let n=t;throw new Ty(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function cX(e,t,n,r,i){for(let n of Object.keys(t))lX.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...lX].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=NN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=cB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=XB(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.
|
|
200
|
+
New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),TW;if(n.kind===`group`){let r=By(e,KW,t,n);return r===null?TW:(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}),JW(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`])}),TW}if(a){let r=By(e,PW,t,n);return r===null?TW:{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=By(e,FW,t,n);return r===null?TW:{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=By(e,IW,t,n);return r===null?TW:{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`])}),TW};function RW(){return{required:!0,json:{type:`object`,propertyNames:{pattern:vx.source},additionalProperties:{$ref:wW}},parse:(e,t,n,r)=>{let i=r[n];if(!Hv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${zy(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!vx.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]=LW(e,`${t}.${n}.${r}`,o)}return a}}}const zW={noun:`root key`,fields:{rows:RW(),when:Zy(),distribution:jW()}};function BW(e,t,n){return Hv(n)&&`rows`in n?By(e,zW,t,n)??{rows:{}}:LW(e,t,n)}const VW={noun:`insert key`,fields:{seg:NW(),id:UB(),before:Zy(),after:Zy()}};function HW(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=By(e,VW,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(eS(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 eS(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 ${zy(t)}`,line:J(e.source,[`insert`])}),[])}function UW(){return{required:!0,json:{type:`string`,pattern:vx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!vx.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 "${ea}", got ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}function WW(){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 ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}}function GW(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Py(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 KW={noun:`layout-node key`,fields:{kind:EW(`group`),name:UW(),label:GW(),open:Qy(),direction:ab(Gv),key:WW(),bg:Zy(),fg:Zy(),when:Zy(),distribution:jW(),children:kW(Yy(()=>LW))}};function qW(e){return e.key??`groups.`+e.name}function JW(e){let t=Jx+e.name;return oa(t,{variable:t,key:qW(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function YW(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function XW(e,t){tP(e,t,Jx,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&YW(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}.`)&&qW(t)===qW(r)&&YW(e,t.path,`group "${t.name}" shares key "${qW(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=qW(t);if(i.has(n)||i.set(n,ea),t.open===!0){let r=i.get(n);r!==`closed`&&YW(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=Jx+e.name,r=qW(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=fa(r,i.get(r)),o[t]=pa(r,e.name),s[t]={template:la(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 ZW=`menu`,QW=`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`,$W=e=>e.kind===`call`&&e.name===`dict`,eG=e=>e.kind===`literal`&&typeof e.value!=`object`,tG=e=>ra(``,e,2)===void 0;function nG(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&&$W(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some($W))return t(`whose options (dict …) is not its last argument — ${QW}`);if(i!==void 0&&a===void 0&&!eG(i)&&tG(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=ra(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${QW}`);let c=a===void 0?{}:qD(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=YM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=eP(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 "${UM(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 rG(e){let t=nE({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===ZW).map(nG)}catch{return`parse-failed`}}function iG(e,t){let n=rG(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:HM(t,e.apply,e.options.key),member:VM(e.apply)}]:[])}function aG(e){let t=nE({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(ZW)}catch{return!1}}function oG(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function sG(e,t){tP(e,t,Yx,`{{ menu }} helpers`),tP(e,t,Xx,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))aG(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`&&aG(i)&&oG(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??{}))aG(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 Zv(Cx(t.root)))typeof n.when==`string`&&aG(n.when)&&oG(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||!aG(r))continue;let n=rG(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:cG(r.apply);n!==void 0&&oG(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function cG(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(VM(e)===`closed`)return`whose apply action is named "${ea}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function lG(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 Mx(e.presets)){let a=new Map,s=new Map;for(let c of Zv(Fx(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,rG(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=qv(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||cG(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=VM(i),f=HM(u,i,l.key),p=GM(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=WM(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]=pa(f,d),n[f]=fa(f,ea),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 uG(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const dG={noun:`style key`,fields:{hueShift:eb(),chromaScale:eb({min:0}),lightnessScale:eb(),lightnessShift:eb()}};function fG(e,t){if(!Hv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${zy(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(Av(r)){e.issues.push({path:`styles.${r}`,message:uG(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=By(e,dG,`styles.${r}`,i);t!==null&&(n[r]={...cu,...t})}return n}const pG={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:BW(e,`${t}.${n}`,r[n])},globals:{required:!1,json:MN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:jN(e,`${t}.${n}`,r[n])}}};function mG(e,t){if(!Hv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${zy(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=By(e,pG,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function hG(e,t){let n=[...t].map(([e,t])=>[tC(e),t]);return t=>{if(QL(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=rC(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function gG(e){return e.kind===`plugin`||e.kind===`missing`}function _G(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>bx(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 Zv(e))t.kind===`segment`&&i(qv(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 vG(e){let t=0,n=hG(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)?[Xv(e,i)]:[],o=e=>a(e)[0]??yG,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>bx(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 yG={kind:`container`,direction:`horizontal`,children:[]};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),[...[...Kx(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=hC(e=>{let i=OC(e,t)?Object.keys(n):wC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=hC(n=>i(n).flatMap(n=>[...bC(n,t).keys()].map(t=>({path:t,reaches:LC(t,e)}))));return{ofTemplate:a,calls:hC(e=>new Set(i(e).flatMap(e=>[...AC(e,t)]))),ofVariable:t=>[...oy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...iy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function xG(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const SG=new WeakMap;function CG(e){let t=SG.get(e);return t===void 0&&(t=bG({names:new Set([...IC(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),SG.set(e,t)),t}function wG(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 TG=new WeakMap;function EG(e){let t=TG.get(e);return t===void 0&&(t=OG(e),TG.set(e,t)),t}function DG(e){return EG(e).projections}function OG(e){let t=new Map(IC(e)),n=new Map,r={reads:CG(e),projections:n,clock:mj};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=xG(e,r),i=t===void 0?null:FM(t);i&&n.set(e,`reads the draw's "${i}" (${PM[i]})`)}let i=AG(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=wG(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of dv)if(!a.has(t))for(let n of i[t]){let i=wG(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=xG(r,i);if(t===void 0||n.has(r))continue;let o=LM(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 kG(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>dv.flatMap(n=>{let r=t[n];return fv(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function AG(e){let t=kG(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function jG(e,t){return wG(e,EG(t))}function MG(e){return t=>wG(t,e)!==null}const NG={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 PG(e,t){let n=new Map;for(let e of Object.keys(t)){let t=BM(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 FG(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 wx(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const IG=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${eC(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${LG(eC(r.definition),n)}${RG(t,n)}`:`${e} entry "${t}" does not match any declared segment${RG(t,n)}`;function LG(e,t){let n=Object.keys(t).filter(tC(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 RG(e,t){return Bz(e)+iC(e,e=>Object.hasOwn(t,e))}function zG(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||fv(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Av(r)?uG(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`])}),PG(e,t.presets);let a=zC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(HG)||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)=>{tR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${tS}" ${tR(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}),nR(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${tS}" 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:NG[a](n),line:i});let o=new Map;for(let e of Zv(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=qv(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=Yv(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`||Kv[e.direction]===`cell`);return Kv[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Kv[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Qv(t,n)]):e.opens===void 0?[]:[[e.opens.body,$v(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=Cx(n),s=bx(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:NG[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of wx(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(iK(e,`${s}.when`,o.when,a,{line:n}),nK(e,`${s}.when`,o.when,n),rK(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(QL(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${tS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${tS}"`,line:n});continue}let c=r(o.name);gG(c)&&(d.add(o.name),e.unplaced.push({path:s,message:IG(i,o.name,t.segments,c),line:n})),XG(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`,Sx(t.root)]]);for(let e of Mx(t.presets)){let{node:n,path:r}=Fx(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 ey(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);gG(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:IG(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}fK(e,t,a,()=>!0)}const BG=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function VG(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!Mx(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Mx(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(`, `)})${Bz(i)}`,line:c})},p=new Set(Jv(Fx(t,a).node)),m=(r,i)=>{!zz.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${Bz(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 HG=`settings.`;function UG(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>HG+e)])}}function WG(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=qG(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of hy(n,KG(n)))i(e,`the defaults do not stand together: ${t}`)}function GG(e){return qG(e).length>0||hy(e,KG(e)).length>0}function KG(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function qG(e){let t=t=>my(JG(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||my(JG(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${YG(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 JG(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function YG(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&my(n)!==void 0).map(([e])=>e)}function XG(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=py(a),s=`${r}: placement "${qv(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(`, `)})`:gy(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?rv(a):``}, but it must be ${by(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])=>gy(o[e],t))||GG(o)))for(let{message:t}of hy(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function ZG(e,t,n,r,i){for(let[a,o]of oy(n))iK(e,`${t}.${a}`,o,r,{segCtx:i})}function QG(e,t,n,r,i){if(!(!iy(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 $G=`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 eK(e,t,n,r){if(!iy(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=jG(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${$G}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=DG(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}: ${$G}`,line:i(`depends_on`)})})}}function tK(e,t){let n=new Map(IC(t)),r=CG(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=dv.find(e=>IM[e]===n||IM[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${IM[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=xG(e,a),s=o===void 0?void 0:LM(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 kG(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 nK(e,t,n,r){try{$N.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function rK(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 wC(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){oK(e,u,`Template references unknown action "${c}"${r}`,aK(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function iK(e,t,n,r,i){let a=(n,r)=>{if(r!==null){oK(e,r,n,aK(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 bC(n,r.helpers)){if(RC(e,r))continue;if(e.startsWith(HG)){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&&RC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Zz(e)}`,t)}for(let{literal:e,via:t}of TC(n,r.helpers))a(`Template spells a link in a grammar older than names, which names no renderer: "${e}". Bind an action instead ({{ action "name" … }}): its link names the renderer that draws it`,t)}function aK(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function oK(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 sK(e,t,n,r,i){let a=n.set,o=hN(nx[r].configKey),s=`${a} takes ${QM(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=uK(n,i);if(c===lK){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=>!ZM(o,e.value,i));if(l.length!==0){if(a===nx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Av(e.value)))){let r=nx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:uG(`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<=cK?r.join(`, `):`${r.slice(0,cK).join(`, `)} and ${r.length-cK} 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 cK=3,lK=Symbol(`any integer`);function uK(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?Hx(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)}]:lK}function dK(e,t){return Object.entries(e).filter(([e])=>t(e))}function fK(e,t,n,r){let i=kR(t),a=Vx(i);for(let[n,o]of dK(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 ${Ux(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;xte.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=lx.get(o.set);s!==void 0&&sK(e,n,o,s,i)}for(let[n,i]of dK(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&&jte(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 dK(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 dK(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=IN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${LN().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=BG.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`){VG(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Mx(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: ${Mx(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${rv(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(`, `)})${Bz(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 dK(t.variables,r)){ZG(e,`variables.${i}`,a,n);let t=Xz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of dK(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))ZG(e,`segments.${i}.vars.${t}`,r,n,i);let r=py(a);if(WG(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=UG({...n,helpers:o},r);for(let n of yH){let c=a[n];typeof c==`string`&&(iK(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),rK(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of dK(t.variables,r))QG(e,`variables.${i}`,a,n),eK(e,`variables.${i}`,a,t);tK(e,t);for(let[i,a]of dK(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))QG(e,`segments.${i}.vars.${r}`,o,n,i),eK(e,`segments.${i}.vars.${r}`,o,t)}function pK(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=mK(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 mK(e){let t=new Map,n=new Map,r=CG(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 hK(e,t,n){let r=new Map([...FC(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 gK(e){return{...TK,config:Fz(TK.raw,e)}}function _K(e,t,n,r,i){let a=MK(e,t,i,(t,a)=>{let o=sH(oH(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>CK(t,n,r,e,i)),s=dH(o,r.beneath.dropped);return{inherited:new Set([...GB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=fH(Fz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(ZV)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const vK=new WeakMap;function yK(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,xK(e.path)])]),a=vK.get(n)??new Map;vK.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=sH(e,t,{config:n,rendering:new Map},(e,t,n)=>CK(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function bK(e,t,n,r){return sH(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>CK(e,t,n,`<plugin install>`,void 0)).dropped}function xK(e){try{let t=h.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function SK(e,t,n,r,i,a=e=>h.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:rc(i.cwd),home:e.homeDir},c=LH(e,s.repo),l=yK(c.definitions,s,n,o),u={...l,dropped:[...l.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let{path:e,scope:n}of t){let t=f.at(-1)?.plugins,i=_K(e,a(e),f.at(-1)?.config??d,{...s,scope:n,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??u.rendering}},o);r.warned(i.warnings),f.push({...i,path:e})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),g=u.dropped.filter(m),_=u.dropped.filter(e=>!m(e));r.warned(g.map(ZV));let v=f.at(-1)?.plugins.rendering??u.rendering,y={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:g,unreached:_,reached:p,rendering:v},b=f.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:f,base:d,installed:y,...x(EK(gK(d),v,`<default>`,o))};try{return{layers:f,base:d,installed:y,...x(EK(b,v,b.path,o,f.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of f.slice(0,-1).entries())EK(t,t.plugins.rendering,t.path,o,f.slice(0,e).reverse());throw e}}function CK(e,t,n,r,i){if(n){EK(wK(e),new Map,r,i);return}let a=tC(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(fK(s,e,zC(e),a),pK(s,e,a),hK(s,e,{checked:a,authored:a}),o.length>0)throw new Cy(r,o)}function wK(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const TK={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function EK(e,t,n=`<config>`,r=new Set(ov()),i=[]){let a=hG(e.config.segments,t),o=OK({...e,path:n},i,a),s=(t,s)=>{let c=Ote(e.config,t,o.authored);return DK(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof Cy)||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 Cy))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,Ix(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function DK({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 Cy(n,[...l,...u.unplaced,...u.inherited],c)};zG(u,a,e,o),pK(u,a),d();let f=AK(n,a.segments,u,o,i,s),p=lG(vG(a),l);d();let m=ZR(pR(p)),h=new Set([...FC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return hK(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function OK(e,t,n){let r=[...t].reverse().concat(e),i=_G(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>gG(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=Ey(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:IG(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function kK(e){if(e.length>0)throw new Ty(e)}function AK(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=FG(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:IG(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new wy(e,t))}function jK(e,t,n=new Set(ov()),r=NK){return MK(e,t,n,()=>({inherited:r,layer:null})).raw}function MK(e,t,n,r){let i=PK(e,t),a=My(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(ov()),groups:[],unplaced:[],inherited:[]};if(!Hv(i))throw new Cy(e,[{path:``,message:`Config root must be an object, got ${zy(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:LK({...c,issues:[]},i.plugins)??[],Hv(i.segments)?Object.keys(i.segments):[]),d=FK(c,i,l,oV(e),e);if(s.length>0)throw new Cy(e,s,o);return{raw:d,warnings:o,layer:u}}const NK=new Set;function PK(e,t){try{return ya.default.parse(t)}catch(t){let n=t;throw new Cy(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function FK(e,t,n,r,i){for(let n of Object.keys(t))IK.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...IK].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=AN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=iB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=KB(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.
|
|
205
201
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
206
202
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
207
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=EJ(e,`root`,t.root)),t.insert!==void 0&&(a.insert=OJ(e,t.insert,i)),t.actions!==void 0&&(a.actions=cV(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=QJ(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=MN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=eY(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=IN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=sV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=uX(e,t.plugins)),IJ(e,a),qJ(e,a),Mte(e,a),iP(e,a,tS,`the global settings menu`),aP(e,a,n),a}const lX=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function uX(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 ${Vy(t)}`,line:J(e.source,[`plugins`])})}const dX={},fX=kI(`commands.`),pX=FI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),mX=CI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),hX=`{{ ${TP} }}`,gX={min:0,max:100,step:5},_X={warnAt:{label:`warning at %`,domain:gX,default:50},errorAt:{label:`error at %`,domain:{...gX,atLeast:`warnAt`},default:80}};function vX(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:gX,default:80}}}const yX={globals:{palette:`tokyo-night`},variables:{...fX.variables,...IM,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:`⊫`},...mX.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:hX},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 ${mX.armed} }}{{ if ne .git.branch "" }} {{ end }}${mX.template}{{ end }}`,fg:hX,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:_I(``).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:fX.template,when:fX.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:vX(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:vX(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:_X,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:_X,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) ${P_} }}`,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:pX.template,bg:pX.bg,when:pX.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:{..._I(``).actions,...fX.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...mX.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...pX.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:dX,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 ${P_} }}{{ \$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 (${TP}) 2 (readableOn (color "accent") (bgOf) ${P_})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${P_}) .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:II(`.`),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 .)) }}`}},bX=new Set([yX.globals.palette,...Object.keys(yX.themeDefaults),...Object.values(yX.segments).map(e=>e.palette)].filter(e=>e!==void 0)),xX=zz(iX(`<default>`,JSON.stringify(yX),bX),yX),SX=Fx(xX.presets);function CX(e){return SX.includes(e)}const wX={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function TX(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function EX(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function DX(e,t,n){return{[EX(lt(e))]:{...wX,cost:t,input:n}}}function OX(e,t){let n=EX(lt(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return I;let a={...wX};return r!==void 0&&TX(a,r),i!==void 0&&TX(a,i),F({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function kX(e,t,n){return ln({dir:e.project_dir,env:n===void 0?[]:[[Oo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const AX=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var jX=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};function MX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function NX(e){return{...Object.fromEntries(Qb.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:CX(e.preset)}}}const PX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function FX(e){if(co(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return co(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const IX=10*1e3;function LX(e,t){if(!(t<60))return e*3600/t}function RX(e,t,n,r){let i=r-t;if(i<50||i>IX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function zX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=RX(t.input,t.atMs,n.input,n.atMs),i=RX(t.output,t.atMs,n.output,n.atMs),a=RX(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 BX(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>IX)continue;let o=RX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function VX(e){return Oq(e.termCols??120)}function HX(e,t){return jo(Ao(e.claudeConfigDir,t))}function UX(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function WX(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${k(t)}`),a=`${e}: ${String(t)}`}n.set(e,tt(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage(r)),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.getContextInfo(r)),c(`metrics`,()=>i.metricsProvider.getMetricsInfo(o,r)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(lt(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(HX(a,i.home)))])}function GX(e,t){let n=Jj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}const KX={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0,showPullRequest:!0};function qX({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,KX,t.workspace?.project_dir]}function JX(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${k(t)}`),Jj(L(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...qX(n))),tmux:i===null?Jj(I):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId))]))},faults:a}}function YX(e){let{hookData:t,deps:n}=e,r=t.session_id,i=n.lanes(),a=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${k(t)}`),L(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:i.git.current(),usage:a(`session`,()=>n.usageStore.usageOf(r,t)),context:a(`context`,()=>n.contextProvider.contextOf(t)),metrics:a(`metrics`,()=>n.metricsProvider.metricsOf(r,t)),activity:a(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:i.tmux.current(),hostName:i.hostName.current(),hostUser:i.hostUser.current(),cache:a(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:a(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:a(`autocompact`,()=>n.autoCompact.stored(HX(e.hints,n.home))),sources:new Map([...i.sources].map(([e,t])=>[e,t.current()]))},today:a(`today`,()=>XX(i.today,n.usageStore,r)),faults:AX.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function XX(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function ZX(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 QX(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?so(t.why):void 0}const $X=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function eZ(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=e.builtins,u={usage:$X(l.session),context:$X(l.context),metrics:$X(l.metrics),activity:$X(l.activity),cache:$X(l.cache),speed:$X(l.speed),autoCompact:$X(l.autocompact),git:$X(l.git),pr:$X(l.pr),tmux:$X(l.tmux),hostName:$X(l.hostName),hostUser:$X(l.hostUser)},d=(e,t)=>{switch(e.kind){case`pending`:return so(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},f=e=>e.kind===`ok`?e.value:void 0,p=i.tmux??null,m=u.git.kind===`pending`?so(u.git.why):u.git.kind===`ok`?pZ(u.git.value,u.pr,so):void 0,h=u.tmux.kind===`pending`?so(u.tmux.why):f(u.tmux)?.session,g=u.hostName.kind===`pending`?so(u.hostName.why):f(u.hostName),_=u.hostUser.kind===`pending`?so(u.hostUser.why):f(u.hostUser),v=QX(u.context)??cZ(u.autoCompact,f(u.context)?.maxTokens),y=r.rate_limits?.five_hour,b=r.rate_limits?.seven_day,x=QX(u.usage,u.metrics)??iZ(f(u.usage)?.session.cost,f(u.metrics)?.sessionDuration),S=d(u.speed,aZ),C=d(u.usage,e=>dZ({cost:e.session.cost,tokens:e.session.tokens})),w=d(u.metrics,e=>dZ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),T=d(u.activity,lZ),E=d(u.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),ee=d(u.cache,e=>({expiresAt:e})),D=fZ(t.home),te=r.workspace?{...r.workspace,current_dir:fZ(r.workspace.current_dir)??``,project_dir:fZ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>fZ(e)??e)}:r.workspace,O=r.session_id;return{...r,...te!==void 0&&{workspace:te},...D!==void 0&&{home:D},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:fZ(r.location.main)??``}},...p!==null&&{tmux:{pane:p.pane,...h!==void 0&&{session:h}}},host:{...g!==void 0&&{name:g},..._!==void 0&&{user:_},...i.ssh!==void 0&&{ssh:i.ssh}},...NX(a),history:n.history,navigation:{back:n.back},term:{cols:VX(i)},...c,...s!==null&&{configPath:s},resumeCommand:kX(te,O,i.claudeConfigDir),...C!==void 0&&{session:C},...x!==void 0&&{burn:x},...S!==void 0&&{speed:S},...y!==void 0&&{block:{nativeUtilization:y.used_percentage,resetsAt:y.resets_at}},...b!==void 0&&{weekly:{percentage:b.used_percentage,resetsAt:b.resets_at}},...ee!==void 0&&{cache:ee},...E!==void 0&&{context:E},...w!==void 0&&{metrics:w},...T!==void 0&&{activity:T},...v!==void 0&&{autocompact:v},...rZ(Object.keys(e.sources),t=>{let n=$X(e.sources[t]);return n.kind===`pending`?so(n.why):n})}}function tZ(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function nZ(e){let t=Object.entries(e);return{runs:String(t.length),runsPending:t.flatMap(([e,{reading:t}])=>t.kind===`pending`?[`${Cn(e)}:${t.why}`]:[]).join(`,`)||`-`}}function rZ(e,t){let n=Object.fromEntries(nC.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 iZ(e,t){let n=e!=null&&t!=null?LX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function aZ(e){let t=zX(e),n=BX(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function oZ(e,t){if(e.kind===`pending`)return so(e.why);if(e.kind!==`ok`)return;let n=OX(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function sZ(e,t,n){await WX(e,t,n),await Gj(()=>{let t=ZX(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function cZ(e,t){switch(e.kind){case`pending`:return so(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return PI(e.value,t)}}function lZ(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=uZ(e.running),i=uZ(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 uZ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function dZ(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 fZ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function pZ(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(kq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Aq(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 mZ=Object.freeze({});function hZ(e,t){return e.kind===`decided`?t[e.name]??mZ:mZ}function gZ(e,t){return{...e,...Object.fromEntries(ex.map(n=>[n,e[n]??t[n]]))}}const _Z=(e,t)=>Sb(n=>{let{setting:r,on:i,inTmux:a}=hb[n].switch;return e[r]===i&&(t||!a)});function vZ(e,t,n,r){let i=tx(e);return sv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function yZ(e,t){return Ix(t(`preset`),e.globals.preset,e.presets)}function bZ(e,t,n){let r=yZ(e,t),i=Bx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=bte(a.palette,t(`theme`),i.palette),s=gZ(i,hZ(o,e.themeDefaults));return{...Object.fromEntries(Qb.map(e=>[e,vZ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:yv(a.style,t(`style`),s.style,e.styles),effect:kv(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const xZ={moving:1e3/30,still:1e3},SZ=[`data`,`state`,`reload`,`visibility`];function CZ(e){return gb.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 wZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const TZ=(e,t)=>hb[t].handsOff?e.resp:e.statusline,EZ=e=>Math.round(1e3/e);var DZ=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)??this.open(e),i={lane:this.laneOf(r,t.lane),sent:null};return r.followers.set(t,i),this.send(t,i),this.hasten(r),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(r,t)}laneOf(e,t){let n=e.lanes.get(t);if(n!==void 0)return n;let r=this.deps.encoders[t](),i={rate:[],encode:r,out:e.last===null?null:r(e.last.bar,TZ(e.last.answers,t))};return e.lanes.set(t,i),i}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 Cb;let r=t-1,i=this.shown(n);return Sb(e=>{let a=n.lanes.get(e)?.rate;if(a===void 0)return bb;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,lanes: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.lanes.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: ${k(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,EZ(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)},a=[...e.lanes].map(([e,n])=>({held:n,out:n.encode(t.bar,TZ(i,e))}));if(!(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline&&a.every(({held:e,out:t})=>e.out?.json===t.json))){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{held:e,out:t}of a)e.out?.json!==t.json&&wZ(e.rate,n),e.out=t;for(let[t,n]of e.followers)this.send(t,n)}}send(e,t){let{out:n}=t.lane;n===null||t.sent===n.json||(e.frame(n),t.sent=n.json)}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:gN(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=eM.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=${EZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${SZ.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}};const OZ=`click.error`;function kZ(e,t,n,r){let i=jZ(e,t).filter(e=>at(e,5,r,`request`)!==`over`);FZ(e,t,{newest:{text:n,at:r,answered:!1},earlier:i})}function AZ(e,t,n){let r=IZ(e,t);if(r===null)return;let i=e=>n.some(t=>ot(e,t))?{...e,answered:!0}:e,a={newest:i(r.newest),earlier:r.earlier.map(i)};a.newest===r.newest&&a.earlier.every((e,t)=>e===r.earlier[t])||FZ(e,t,a)}function jZ(e,t){let n=IZ(e,t);return n===null?[]:[...n.earlier,n.newest]}function MZ(e,t,n,r){return jZ(e,t).map(e=>({error:e,hold:at(e,5,n,r)}))}const NZ=e=>e.flatMap(({error:e,hold:t})=>t===`over`?[]:[e]),PZ=e=>NZ(e).filter(e=>!e.answered);function FZ(e,t,{newest:n,earlier:r}){e.set(t,OZ,JSON.stringify({...n,earlier:r}))}function IZ(e,t){let n=e.get(t,OZ);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return null}let i=LZ(r);if(i===null)return null;let{earlier:a}=r;return{newest:i,earlier:Array.isArray(a)?a.flatMap(e=>{let t=LZ(e);return t===null?[]:[t]}):[]}}function LZ(e){if(typeof e!=`object`||!e)return null;let{text:t,at:n,answered:r}=e;return typeof t==`string`&&typeof n==`number`&&(r===void 0||typeof r==`boolean`)?{text:t,at:n,answered:r===!0}:null}function RZ(e,t){return gb.filter(n=>e[n]&&hb[n].handsOff&&t.has(n))}function zZ(e,t,n){return{severity:_U,lines:[[vU(`[⟲ claude]`,GS(e,[{verb:xS,args:[t,...n.map(e=>hb[e].switch.setting)]}]))]]}}function BZ(e,t){for(let n of Object.entries(t))e.push(n)}const VZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function HZ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,k(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function UZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...HZ(n)];return{level:VZ[n.kind],line:WZ(e,i)}}const WZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function GZ(e,t,n){if(t.kind===`pending`)return so(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}const KZ=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`]),qZ=[[`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`]],JZ=[[`workspace.added_dirs`,`string-list`]];function YZ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of qZ){let i=QZ(n,e);if(i==null)t.missingRequired.push(e);else{let n=XZ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of JZ){let i=QZ(n,e),a=i===void 0?r:ZZ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))KZ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function XZ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function ZZ(e){return Array.isArray(e)&&e.every(e=>XZ(e)===`string`)?`string-list`:XZ(e)}function QZ(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 $Z(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 eQ(e){let t=$Z(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}new Set(AX);function tQ(e){return{hookData:e.hookData,cwd:e.cwd,hints:e.hints}}function nQ(e){let t=e.kind===`recording`?{kind:e.kind,v:5,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,request:e.request,state:{...e.state,idleSince:e.state.idleSince??null},diagnostics:e.diagnostics}:e.kind===`turn`?{kind:e.kind,held:e.held,at:e.document.at,facts:e.document.facts,...tQ(e.request),state:e.state}:{kind:e.kind,...e.kind===`request`&&{at:e.at},...tQ(e.request)};return`${JSON.stringify(t)}\n`}function rQ(e,t){let n=new Map,r=!1,i=e=>{for(let t of e.watching)t();e.watching.clear()},a=(e,t,r)=>{let a=n.get(e);a===void 0||!a.delete(t)||(a.size===0&&n.delete(e),i(t),t.sink.end(r))},o=(e,n,r)=>{if(!(r.kind===`facts`&&r.facts===n.document)&&!(r.kind===`declared`&&r.request===n.declaration))try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),r.kind===`turn`&&(n.document=r.document.facts),(r.kind===`request`||r.kind===`declared`||r.kind===`turn`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${k(r)}`),a(e,n,{kind:`failed`,error:r})}},s=(e,t,n)=>{let r=n.source.held();t.turn?.view===n&&t.turn.held===r||(t.turn={view:n,held:r},o(e,t,{kind:`turn`,held:r,...n.source.turn()}))},c=(t,r)=>{let i=e.sessionView(t);if(i===null)return;let a=(e,i)=>{if(!n.get(t)?.has(r))return;let a=(0,X.reaction)(e,i,{fireImmediately:!0});n.get(t)?.has(r)?r.watching.add(a):a()};a(()=>i.source.held(),()=>s(t,r,i)),a(()=>i.followed.stamped(),e=>o(t,r,{kind:`facts`,...e}))};return{record(t,i){if(r)throw Error(`the daemon is closing: it records nothing more`);let s=e.sessionView(t);if(s===null)throw Error(`no view of session ${JSON.stringify(t)} is open in this daemon: it has not drawn a bar here since the daemon started, or its view closed while it was idle`);let l={sink:i,watching:new Set,document:null,declaration:null,turn:null},u=n.get(t)??new Set;return n.set(t,u.add(l)),o(t,l,{kind:`recording`,session:t,home:s.source.home()}),u.has(l)&&c(t,l),()=>a(t,l,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])i(t),c(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])o(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(t,{at:r,noted:i},{view:a,state:c,diagnostics:l}){let u=e.sessionView(t);for(let e of n.get(t)??[]){if(!i.has(e))continue;let d=[()=>s(t,e,a),()=>o(t,e,{kind:`facts`,...a.followed.stamped()}),()=>o(t,e,{kind:`declared`,request:a.facts()}),()=>o(t,e,{kind:`draw`,request:r,state:c,diagnostics:l}),...u===null?[]:[()=>s(t,e,u)]];for(let r of d)n.get(t)?.has(e)&&r()}},close(){r=!0;for(let[e,t]of n)for(let n of t)a(e,n,{kind:`closed`})}}}function iQ(e,t){let n=null,r=rQ({sessionView:e=>{if(n===null)throw Error(`a recorder read its cache before the cache was built`);return n.sessionView(e)}},t);return n=e({onSessionViewMoved:e=>r.moved(e)}),{cache:n,recorder:r}}function aQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}function oQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,{view:t,state:{...t.source.state(),idleSince:i.idleSince},diagnostics:i.diagnostics}),i}var sQ=class extends Error{name=`RecordingFailed`};function cQ(e,t,n,r,i,a){return new Promise((o,s)=>{let c;try{c=C(r,`wx`,384)}catch(e){s(Error(e.code===`EEXIST`?`${r} already exists: a recording writes a new file`:`${r} cannot be created: ${String(e)}`));return}let l=0,u=0,d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{g(c,nQ(e)),l++,e.kind===`draw`&&u++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{_(c),u===0&&D(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u,daemonClosed:e.kind===`closed`}):s(new sQ(`writing ${r}: ${String(t)}`))}};a.addEventListener(`abort`,p,{once:!0});try{d=e.record(n,m)}catch(e){a.removeEventListener(`abort`,p),f(),_(c),D(r),s(e)}})}const lQ=()=>{},uQ=e=>({ok:!1,error:e instanceof Error?e.message:k(e),code:`RENDER_FAILED`,daemonV:3}),dQ={ansi:e=>({ok:!0,output:ane(e)}),frame:e=>({ok:!0,frame:e})};function fQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=uo();let i=c.u(yQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=xQ(e,i,{by:`feed`,fps:n}),p=dQ.ansi(o.body),m=DQ(e.links.to,t,o,RZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:dQ.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}=UZ(`render`,s,{kind:`threw`,error:e},tt(i,o)),r=uQ(e);return{bar:$te(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:lQ,failure:{level:t,line:`frame ${n}`}}}}function pQ(e,t,n){let{sessionState:r}=e;return bZ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function mQ(e,t){try{var n=uo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:_Z(i.view.source.effective(),gc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function hQ(e,t,n){let r=e.frameFeeds.latest(n);return gQ(e,t,n,r===null||gc(r.hints.tmux))}function gQ(e,t,n,r){try{var i=uo();return _Z(pQ(e,n,i.u(e.renderCache.hold(t.projectDir,t.cwd,t.target.path)).state),r)}catch(e){i.e=e}finally{i.d()}}function _Q(e,t,n,r){BZ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=br(e,i),o=xr(a);return BZ(n,{termCols:String(i.termCols??`?`),termRows:String(i.termRows??`?`),refused:a.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:i.client?.kind??`unreported`,rateLimits:e.rateLimits}),o}function vQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&s.isAbsolute(a)&&{location:fc(a)}}},c=_Q(o,n,r,e.rendererName);BZ(r,{encoding:o.encoding});let l=o.requested;return bQ(i.holdSession(l.projectDir,l.cwd,l.target.path,o),o,c,n,r)}function yQ(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=_Q(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return bQ(a,o,s,n,r)}function bQ(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c}=t;return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function xQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkIds:s,links:c,fileEvents:l,renderWarnings:u,payloadProviders:d,effectSessions:f,menuIdle:p,launcher:m}=e,{req:h,at:g,facts:_,sessionId:v,entry:y,state:b,view:x,hintsError:S}=t,C=x.source.payload(),w=x.source.effective(),T=x.source.failure(),E=_Z(w,C.tmux!==void 0);BZ(_,{lanes:gb.filter(e=>E[e]).join(`,`)||`-`});let ee=x.source.hints(),D=C.term.cols;BZ(_,{width:String(D)});let te=MZ(r,v,g,n.by),O=o.notice({to:c.to,sessionId:v,dismissed:r.get(v,Pz),enabled:w.updateNotice}),k=GU(y.repos,v,c),ne=(e,t)=>({about:e,text:t,copy:t}),A=e=>ne(e??``,e),re=[A(Cr(h.refusedArgs)),A(S),ne(`load`,y.lastError),ne(`update-act`,o.error()),ne(`link-ids`,s.error()),...b.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),...NZ(te).map(e=>ne(`click\0${e.at}\0${e.text}`,e.text))].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ie=y.watch===null?null:kj(`config watch`,y.watch,null),ae=m.launcherWarnings(g,n.by),oe=ae.find(e=>e.kind===`launch-pipes`),se=oe?.event??null,ce=[...jc(l.delivery()),...ae,...ie===null?[]:[{kind:`config-watch`,message:ie}],...y.lastWarning===null?[]:[{kind:`load`,message:y.lastWarning}],...T===null?[]:[{kind:`facts`,message:T.cause===`inputs`?`the bar is held on the last turn taken: ${T.reason}`:`the bar is drawn from the last facts that were read; the next could not be stamped: ${T.reason}`}]],le={config:b.config},ue=yU(c.to,v,n.by,re,[...O,...k],[...ce.map(e=>({about:e.kind,message:e.message})),...u.ofSession(v,n.by,le).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),de=x.source.facts(),fe={diagnostics:kU(ue),drawing:n,feeds:i.feedsOf(v,g),today:oZ(de.builtins.today,g)},pe=co(C.metrics)?void 0:C.metrics;BZ(_,tZ(de.sources)),BZ(_,nZ(de.runs)),BZ(_,{factsSeq:String(de.seq),prompts:String(pe?.messageCount??`-`),nonPrompts:String(pe?.nonPrompts??`-`),pr:FX(C.git),feeds:CZ(fe.feeds)});let me=[],he=MX(w,D),ge=f.of(v),{frame:_e,evaluated:ve,cellBreaks:ye,rules:be,idleSince:xe}=p.drawn(v,g,w.menuTimeout,e=>Dq(b.config,b.compiled,x.store,x.registry,fe,g,he,{perSegmentSink:x.lastRenderCellsBySegment,onRenderWarning:e=>me.push(e)},{...w,effects:ge,idleSince:e})),Se=xU(ue),Ce=new Map(ue.map((e,t)=>[Se[t],e.copy])),we=()=>a.delivered(v,n.by,Ce),Te=p.since(v,g);BZ(_,{menuIdle:Te===void 0?`-`:`${(g-Te).toFixed(1)}s/${w.menuTimeout}s`});let Ee=u.drawn(v,n.by,le,me),De={width:D,rows:jU(ee.termRows,n.by===`feed`?gb.flatMap(e=>{let t=hb[e].rows;return E[e]&&t!==null?[t]:[]}):[]),colorCompatibility:_e.depth},Oe=AU(r.get(v,sS),ue),ke=Oe===null?_e:qP(_e,MU(ue,Oe,c.to,v,n.by,De)),Ae=d.gitProvider.getStats(),je=d.usageStore.getStats(),Me=ge.lastFrame(),Ne=Me.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Pe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Fe=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ie=[...ce,...me].map(Fe).join(`,`)||`-`;return BZ(_,{git:`${Ae.size}/${Ae.hits}h/${Ae.misses}m`,usage:`${je.size}/${je.hits}h/${je.misses}m`,effect:Me.effect,effectT:Me.t.toFixed(3),speed:`${Me.speed}x`,effectRows:`${Me.made}made/${Me.reused}reused`,effectOwn:Ne,fadeBasis:Me.basis,stateRev:String(Me.revision),fades:Pe(Me.fades),leaves:Pe(Me.leaves),motion:ke.motion,evaluated:String(ve),cellBreaks:String(ye),pending:ke.pending.join(`,`)||`-`,rules:[...be].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:re.length>0?`Y`:`N`,clickError:te.map(({hold:e})=>e).join(`,`)||`-`,pipeEvent:oe?.hold??`-`,upd:String(O.length),ask:String(k.length),warn:Ie,diag:String(ue.length),warnRecord:Ee?`new`:`kept`,viewer:Oe===null?`-`:`${Oe.index}/${ue.length}p${Oe.page+1}`}),{drawn:{body:ke,viewerOpen:Oe!==null,diagnostics:ue,geometry:De},evaluated:ve,cellBreaks:ye,answersClick:PZ(te),pipeShown:se,delivered:we,lanes:E,idleSince:xe}}function SQ(e,t){let{laneSetups:n,tmuxStatusLines:r}=e,i=gQ(e,t.requested,t.sessionId,gc(t.hints.tmux));return r.observe(t.sessionId,t.hints.tmux,i.tmuxStatus),n.noted(t.sessionId,i)}function CQ(e,t,n){return oQ(e.recorder,t.view,n,()=>{let n=xQ(e,t,vb);return{...n,diagnostics:n.drawn.diagnostics}})}function wQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:dF(e.hookData)}}function TQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);return s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus),a.clicked(t,n,r)}async function EQ(e,t,n,r,i){try{var a=uo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(vQ(e,t,n,i)),u=aQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;BZ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Kj(e=>Promise.all([u.landed,l.view.registry.inFlight(e)]),f,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${k(e)}`),o.after),m=o.monotonic();BZ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:UX(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=CQ(e,l,u.arrival),b=t.sessionId,x=RZ(y,s.following(b)),S=fF(t.hints.client??null)===`statusline`,C=dQ[t.encoding](S?DQ(e.links.to,b,h,x):h.body);return BZ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${tt(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function DQ(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:qP(n.body,NU(zZ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const OQ=/^─{20,}/,kQ=/^❯(\s|$)/,AQ=/›\s*stashed$/;function jQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>OQ.test(e)?[t]:[]).at(-2);return n===void 0||!kQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function MQ(e){if(e.inMode)return{kind:`in-mode`};let t=jQ(e);return t===null?{kind:`no-prompt`}:AQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function NQ(e){return/^❯\s*\S/u.test(jQ(e)?.prompt??``)}const PQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function FQ(e){return e.screen.some(e=>PQ.test(e))}const IQ={"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 LQ(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 RQ(e,t,n){let r=MQ(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:IQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function zQ(e,t,n,r,i){let a=await Ws(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function BQ(e,t){let n=await zQ(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(`
|
|
208
|
-
`);return{inMode:r!==`0`,screen:i}}function VQ(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 HQ(e,t,n){let r=await zQ(e,t,`claude-input.type`,VQ(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 UQ(e){return{read:t=>BQ(e,t),type:(t,n)=>HQ(e,t,n)}}const WQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`,run:({run:e})=>`run:${e.action}`,"lane-setup":({lane:e,on:t})=>`lane-setup:${e}-${t?`on`:`off`}`,doctor:({step:e})=>`doctor:${e.kind}`};function GQ(e){let t=WQ[e.kind];return t(e)}const KQ=`render-origin`,qQ=`client-hints`;function JQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Rv:zv;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const YQ=Object.entries(ax),XQ=new Set(sx.map(e=>e.sessionKey)),ZQ=()=>!1;function QQ(e,t){return bZ(e,e=>XQ.has(e)?t(e):null,ZQ)}const $Q=[`preset`,`theme`];function e$(e,t,n){let r=new Set($Q.slice(0,n).map(e=>ax[e].sessionKey));return bZ(e,e=>r.has(e)?t(e):null,ZQ)}function t$(e,t){let n=Array.from({length:$Q.length+1},(n,r)=>e$(e,t,r));return e=>{let t=$Q.indexOf(e);return n[t===-1?$Q.length:t]}}function n$(e,t,n,r){return e.flatMap(([e,i])=>{let a=JQ(t,e);return a===null||a===JQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function r$(e,t,n){return JQ(QQ(e,t),n)}function i$(e,t){let n=QQ(e,t);return n$(YQ,n,t$(e,t),t=>a$(e,n.preset,t.configKey))}function a$(e,t,n){return n in(Lx(e.presets,t).globals??{})?XN(t,n):n}function o$(e,t,n){let r=Ix(t(ax.preset.sessionKey),e.globals.preset,e.presets),i=ZN(n);return{key:i?.scope===`globals`?a$(e,r,i.field):n,globals:Bx(e,r)}}function s$(e,t){let{preset:n}=QQ(e,t);return u$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:by(a,s);return c===void 0||yy(c)===yy(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function c$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Fx(e.presets).flatMap(n=>{let i=u$(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 _y(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:by(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const l$=new WeakMap;function u$(e,t){let n=l$.get(e)??new Map;l$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...$v(Rx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=hy(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 d$(e,t){let n=QQ(e,t);return{from:n.preset,globals:Lx(e.presets,n.preset).globals??{},picks:n$(YQ.filter(([e])=>e!==`preset`),n,t$(e,t),e=>e.configKey),placements:s$(e,t)}}function f$(e,t){return bZ({...e,globals:{palette:t},presets:{}},()=>null,ZQ)}function p$(e,t){let n=QQ(e,t),r=JQ(n,`theme`);if(r===null)return{kind:`rule`};let i=f$(e,r),a=Bx(e,n.preset),o=Object.fromEntries(ex.map(e=>[e,JQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:ex.some(e=>o[e]!==JQ(i,e))}}function m$(e){return{sessionKeys:sx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...ON(e)?SX.map(t=>XN(t,e)):[],...YN(e)?cv().map(t=>JN(t,e)):[]]}}function h$(e){return new Set(sx.map(e=>e.configKey).filter(t=>m$(t).fileKeys.some(t=>v$(e,_$(t)))))}function g$(e,t,n){let r=i$(e,n),i=new Set(r.map(e=>e.configKey)),a=dx(e=>i.has(ax[e].configKey)||t.has(ax[e].configKey)),o=p$(e,n);return{unsaved:r.length+s$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function _$(e){let t=ZN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return QN(t)}function v$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&v$(e[n],r)}function y$(e,t,n){let r=fx.get(n);if(r!==void 0)return r$(e,t,r);for(let[,t]of dy(e))if(t.key===n)return t.default??null;return null}function b$(e,t){let n=HN(e).get(t);return n===void 0?null:String(n)}const x$={inside:()=>[],defaultOf:()=>ea,menus:[]},S$=e=>`${e.key}\0${e.member}`;function C$(e){let t=new Map,n=n=>{let r=`${n.name}\0${Yv(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:WJ(a,Yv(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(S$(e))??new Map;n.set(S$(t),t),o.set(S$(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(S$(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 Fx(e.presets))d(Rx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ma(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(S$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(S$(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(S$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const w$=new WeakMap;function T$(e){let t=w$.get(e);if(t!==void 0)return t;let n=C$(e);return w$.set(e,n),n}function E$(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 D$(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 O$(e,t,n){let r=(r,i,a)=>{let o=E$(t(r),t=>e.get(r,t),i);(0,X.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),values:t=>e.values(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 k$=new Set([`1`,`true`]),A$=new Set([`0`,`false`,``]);function j$(e,t){let n=n1(e),r=n.scope===`segment-palette`?`string`:rx(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(k$.has(t))return`true`;if(A$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function M$(e){try{return h.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function N$(e,t,n){try{if(t===null){h.rmSync(or(Pn,e),{force:!0});return}dr(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function P$(e){return/^\s*$/.test(e)?null:wa(e)}function F$(e,t){return e!==null&&Ea(e,t)!==void 0}function I$(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(I$),...i}}return e}function L$(e){if(!Cx(e))return I$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,I$(t)])),...n}}const R$=yX,z$=R$.segments,B$=R$.presets,V$=R$.root;function H$(e,t,n,r){if(!F$(e,t)&&n===void 0)throw new R(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function U$(e,t){let n=QN(t);return t.scope===`segment-palette`&&H$(e,[`segments`,t.segment],z$[t.segment],n.join(`.`)),n}function W$(e){return wa(Pa(e))}function G$(){return Object.entries(V$.rows).map(([e,t])=>{let n=I$(t);return{path:[`root`],fragment:W$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function K$(e,t){let n=e===null?void 0:Ea(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function q$(e,t){if(t===void 0)return null;let n=L$(t);return{path:e,fragment:W$(n),unit:{path:e,value:n}}}function J$(e,t){let n=[`presets`,t],r=[...n,`root`],i=B$[t];H$(e,n,i,r.join(`.`));let a=K$(e,r)??q$(r,i?.root);return a!==null&&eo(a.fragment)?a:null}function Y$(e,t){let n=$a(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 X$(e,t){return[...G$(),K$(e,[`root`]),J$(e,t)].filter(e=>e!==null).reduce(Y$,new Map)}function Z$(e,t,n){for(let{node:r,...i}of X$(e,t).values())if(no(r,n))return i;throw new R(`${Q$(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 Q$(e,t){return J$(e,t)?.path??[`root`]}function $$(e,t){return t.scope===`preset-root`?Q$(e,t.preset):QN(t)}function e1(e,{unit:t}){return t===null?e:qa(e,t.path,Pa(t.value),Ma)}function t1(e){let t=ZN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function n1(e){let t=t1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function r1(e,t,n,r,i){let a=m1(t,r),o,s=()=>(o??={chain:c1(t,n)}).chain;h1(t,s,a),i(t,s,a),N$(t.path,r,e.logger),e.record(t.path,n,r)}function i1(e,t,n){let r=s1(e,t(),n);if(r.length>0)throw new R(`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 a1=()=>{};function o1(e,t){try{return t()}catch(t){throw!(t instanceof R)||e.above.length===0?t:new R(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function s1(e,t,n){if(t===null)return[];let r=new Set(f1(d1(t),d1(n)));return f1(u1(e,t),u1(e,n)).filter(e=>!r.has(e))}function c1(e,t){try{return l1(e,t)}catch(e){if(e instanceof Ty)return null;throw e}}function l1(e,t){return YY(e.locs,t===null?e.above:[rU(e.path),...e.above],xX,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:h.readFileSync(n,`utf8`))}function u1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function d1(e){return e.layers.at(-1)?.config??e.base}function f1(e,t,n=``){return!p1(e)||!p1(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>f1(e[r],t[r],n===``?r:`${n}.${r}`))}function p1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function m1(e,t){try{return l1(e,t)}catch(e){throw e instanceof Ty?new R(`refused: the config file would not load after this click — ${e.message}`):e}}function h1(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 R(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new Ty(e,[t]).message).join(`
|
|
209
|
-
`)}`)}function g1(e,t){let n=n1(t),r=P$(M$(e)??``),i=r===null?void 0:Ea(r,QN(n));return i!==void 0&&`value`in i?i.value:void 0}function _1(e,t,n){v1(e,t,n,[])}function v1(e,t,n,r){let i=M$(t.path),a=n.reduce((e,[t,n])=>qa(e,U$(P$(e),n1(t)),j$(t,n),Ma),i??``);r1(e,t,i,o1(t,()=>y1(a,t.path,r,e=>e)),i1)}function y1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Z$(P$(s),n,i),l=aee(e1(s,c),c.path,i,a,Pa(o));if(l===null)throw new R(`${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 b1(e,t,n){let r=P$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of X$(r,t)){if(!no(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Oa(e,c):Pa(s.value);if(a!==`#`)return qa(e,[...i,`rows`,a],l,Ma);if(J$(r,t)!==null)throw new R(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return qa(e,i,l,Ma)}return e}function x1(e,t){return Ya(e,t,t[0]===`presets`&&t.length>2&&!CX(t[1])?2:0)}function S1(e,t,n){let r=n.map(t1),i=M$(t.path);if(i===null)return;let a=r.reduce((e,t)=>x1(e,$$(P$(e),t)),i);a!==i&&r1(e,t,i,a,a1)}function C1(e){let t=e===null?void 0:Ea(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function w1(e,t){let n=new Set([...SX,...C1(e),...t.above.flatMap(e=>Object.keys(ya.default.parse(h.readFileSync(e.path,`utf8`)).presets??{}))].map(UM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(UM(e)))}function T1(e,t,n,r,i,a){let o=M$(t.path),s=P$(o??``),c=w1(s,t),l=[`presets`,c],u=o1(t,()=>J$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Oa(o??``,u.fragment):Pa(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Pa(r)]]],f=i.map(([e,t])=>{let n=XN(c,e);return[U$(s,n1(n)),j$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>qa(e,t,n,Ma),qa(o??``,l,`{}`,Ma));return r1(e,t,o,o1(t,()=>y1(p,t.path,a.map(e=>({...e,preset:c})),b1)),i1),c}function E1(e,t,n,r){let i=M$(t.path);r1(e,t,i,qa(i??``,[`themeDefaults`,n],Pa(r),Ma),i1)}function D1(e,t,n){if(CX(n))throw new R(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=M$(t.path),a=P$(i??``);if(i===null||a===null||Ea(a,r)===void 0)throw new R(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ea(a,[`globals`,`preset`]);r1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>x1(e,t),i),a1)}function O1(e,t,n,r){let i=t1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=M$(t.path),o=r.op===`remove`?r.target:r.anchor,s=o1(t,()=>Z$(P$(a??``),i.preset,o)),c=e1(a??``,s),{after:l,placed:u}=k1(c,s.path,r,()=>{let e=m1(t,c).config;return Fx(e.presets).map(t=>Rx(e,t).node)});if(l===null)throw new R(`${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 r1(e,t,a,l,i1),u}function k1(e,t,n,r){switch(n.op){case`remove`:return{after:ree(e,t,n.target),placed:null};case`insert`:{let i=iz(n.segment,n.anchor,r());return{after:iee(e,t,i,n.anchor,n.relation),placed:i}}}}const A1={inTurn:()=>`single-run`};function j1(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),values:t=>e.values(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 M1={load:()=>({}),save:()=>{},flush:()=>{}};var N1=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e,t=M1,n=256){this.turns=e,this.maxSessions=n,this.storage=t,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).filter(([,e])=>Object.keys(e).length>0).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}values(e){return this.atom.reportObserved(),Object.fromEntries(this.sessions.get(e)?.values??[])}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){this.held(e),t.length!==0&&this.commit(e,e=>{t.some(({key:t,value:n})=>e.values.get(t)!==n)&&(e.revision=++this.head);for(let{key:n,value:r}of t)e.values.set(n,r)})}clear(e,t){this.held(e),this.commit(e,e=>{e.values.delete(t)&&(e.revision=++this.head)})}restore(e,t,n){this.held(e),(this.sessions.get(e)?.revision??0)!==n&&this.commit(e,e=>{e.values.clear();for(let[n,r]of Object.entries(t))e.values.set(n,r);e.revision=n,this.head=Math.max(this.head,n)})}commit(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t(n),n.values.size===0?this.sessions.delete(e):(this.touch(e,n),this.evictOldest()),this.persist(),this.atom.reportChanged()})}held(e){if(this.turns.inTurn()===null)throw Error(`session state: a write of ${JSON.stringify(e)} outside any turn`)}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=M1}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function P1(e){let t=new Map;return{dir:e.dir,onDisk:n=>{let r=t.get(n);if(r!==void 0)return r;let i=e.onDisk(n);return t.set(n,i),i}}}function F1(e,t){return z1(e.dir,t)??I1(e,t)}function I1(e,t){let n=e.onDisk(e.dir);for(let r of L1(t)){let i=R1(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function L1(e){let t=s.dirname(e);return t===e?[]:[t,...L1(t)]}function R1(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function z1(e,t){let n=R1(e,t);return n===``?null:n}function B1(e,t){let n=F1(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var V1=class extends Error{};function H1(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new V1(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return U1(e,t)}if(typeof t!=`object`||!t)throw new V1(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new V1(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||z1(e.dir,t)!==r)throw new V1(`stored home path ${JSON.stringify(r)} is not a plain path inside the home's root ${e.dir}`);return t}if(n===`world`){if(!s.isAbsolute(r))throw new V1(`stored world path ${JSON.stringify(r)} is not absolute`);if(z1(e.dir,r)!==null)throw new V1(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return U1(e,r)}throw new V1(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function U1(e,t){let n=F1(e,t);return n===null?t:s.join(e.dir,n)}const W1={load:()=>({}),save:()=>{}},G1=new Set(sx.map(e=>e.sessionKey)),K1=e=>G1.has(e)||e.startsWith(uP),q1=8*1024*1024,J1={past:[],future:[]},Y1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var X1=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=W1){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)??J1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??J1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(Y1(r));i.set(Y1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:j1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!K1(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:i0(i,r),o=n.get(e),s=o===void 0?a:c0(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 R(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,o0(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new R(`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(Y1)),a=n.net.filter(e=>!i.has(Y1(e))),o=$1(l0(s0(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new R(`rewind: ${r.map(d0).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 R(`redo: nothing to redo`);let a=[...n,i],o=$1(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...t0(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(Y1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:l0(n,t),future:l0(i,t),...a!==void 0&&{savepoint:{at:l0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(Y1(e))),below:l0(a.below,t)}}}),new R(`${r}: ${o.map(d0).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):M$(t.file)}write(e,t,n){t.kind===`file`?N$(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||Z1(n)>q1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,Q1(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${q1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function Z1(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 Q1({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...t0(n,1,[])}:{past:e,future:t.slice(1),...t0(n,0,[])}}function $1(e){return e.slice(-50)}const e0=e=>e===fP.member;function t0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:n0(e.net,n),below:e.below}}}function n0(e,t){let n=new Map(e.map(e=>[Y1(e),e]));for(let e of t){let t=n.get(Y1(e));n.set(Y1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const r0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function i0(e,t){let n=[...e.past,t],r=$1(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...t0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...a0(e.future,a),...i.below]},n.length-r.length,t)}}function a0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function o0(e,t){return{past:e.past.slice(0,-1),future:$1([...e.future,t]),...t0(e.savepoint,0,r0(t))}}function s0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...a0(r,t.at-i.length),...t.below]}function c0(e,t){if(e0(t.after)&&!e0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!e0(t.after)&&e0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function l0(e,t){return e.map(e=>e.filter(e=>!t.has(Y1(e)))).filter(e=>e.length>0)}function u0(e){return e.map(d0).join(`, `)}function d0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function f0(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`&&`file`in t)&&n(t.before)&&n(t.after)}function p0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(f0))}function m0(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(f0)&&p0(t.below)}function h0(e){if(typeof e!=`object`||!e)return!1;let t=e;return p0(t.past)&&p0(t.future)&&(t.savepoint===void 0||m0(t.savepoint))}function g0(e,t){let n=e=>e.kind===`file`||K1(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 _0(e,t){let n=(e,n)=>e.map(e=>e.kind===`file`?{...e,file:t(e.file,n)}:e),r=(e,t)=>e.map((e,r)=>n(e,`${t} step ${r+1}`)),{past:i,future:a,savepoint:o}=e;return{past:r(i,`undo`),future:r(a,`redo`),...o!==void 0&&{savepoint:{at:o.at,net:n(o.net,`edit mode's change`),below:r(o.below,`edit mode's redo`)}}}}function v0(e,t,n){return{load:()=>{let r;try{r=h.readFileSync(e,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&n(`warn`,`settings-history read failed (${t}); starting empty`),{}}let i;try{i=JSON.parse(r)}catch{i=null}if(typeof i!=`object`||!i||Array.isArray(i)||!Object.values(i).every(h0))return n(`warn`,`settings-history load: unexpected shape, starting empty`),{};let a=P1(t),o;try{o=Object.entries(i).map(([e,t])=>[e,_0(t,(t,n)=>{try{return H1(a,t)}catch(t){throw t instanceof V1?new V1(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof V1))throw e;return n(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let s=new Set,c=Object.fromEntries(o.map(([e,t])=>[e,g0(t,s)]));return s.size>0&&n(`warn`,`settings-history load: dropped the changes to ${[...s].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),c},save:r=>{let i=P1(t),a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,_0(t,e=>B1(i,e))]));try{h.mkdirSync(s.dirname(e),{recursive:!0}),dr(e,JSON.stringify(a),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw n(`error`,t),Error(t)}}}}const y0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function b0(e){return{...Object.fromEntries(y0.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 x0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function S0(e){let t=e=>({kind:`failed`,reason:e});if(!x0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!x0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!TF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${TF.join(` or `)}`)}return{kind:`ok`,value:e}}function C0(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const w0=e=>fU(e,`doctor-marks.json`,{},S0),T0=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],D0=e=>fU(e,`doctor-clicked-terminals.json`,[],T0);var O0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const k0=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),j0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=A0(e,t);return r===void 0?n:r.projectDir},M0=(e,t)=>A0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function N0(e){let t=new Map;for(let n of e.split(`
|
|
210
|
-
`)){
|
|
203
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=BW(e,`root`,t.root)),t.insert!==void 0&&(a.insert=HW(e,t.insert,i)),t.actions!==void 0&&(a.actions=iV(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=fG(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=kN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=mG(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=NN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=rV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=LK(e,t.plugins)),XW(e,a),sG(e,a),Fte(e,a),tP(e,a,Qx,`the global settings menu`),nP(e,a,n),a}const IK=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function LK(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 ${zy(t)}`,line:J(e.source,[`plugins`])})}const RK={},zK=TI(`commands.`),BK=jI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),VK=yI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),HK=`{{ ${SP} }}`,UK={min:0,max:100,step:5},WK={warnAt:{label:`warning at %`,domain:UK,default:50},errorAt:{label:`error at %`,domain:{...UK,atLeast:`warnAt`},default:80}};function GK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:UK,default:80}}}const KK={globals:{palette:`tokyo-night`},variables:{...zK.variables,...NM,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:`⊫`},...VK.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:HK},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 ${VK.armed} }}{{ if ne .git.branch "" }} {{ end }}${VK.template}{{ end }}`,fg:HK,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:pI(``).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:zK.template,when:zK.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:GK(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:GK(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:WK,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:WK,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) ${M_} }}`,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:BK.template,bg:BK.bg,when:BK.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:{...pI(``).actions,...zK.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...VK.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...BK.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:RK,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 ${M_} }}{{ \$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 (${SP}) 2 (readableOn (color "accent") (bgOf) ${M_})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${M_}) .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:MI(`.`),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 .)) }}`}},qK=new Set([KK.globals.palette,...Object.keys(KK.themeDefaults),...Object.values(KK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),JK=Fz(jK(`<default>`,JSON.stringify(KK),qK),KK),YK=Mx(JK.presets);function XK(e){return YK.includes(e)}const ZK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function QK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function $K(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function eq(e,t,n){return{[$K(lt(e))]:{...ZK,cost:t,input:n}}}function tq(e,t){let n=$K(lt(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return I;let a={...ZK};return r!==void 0&&QK(a,r),i!==void 0&&QK(a,i),F({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function nq(e,t,n){return ln({dir:e.project_dir,env:n===void 0?[]:[[Oo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const rq=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var iq=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};function aq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function oq(e){return{...Object.fromEntries(Xb.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:XK(e.preset)}}}const sq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function cq(e){if(co(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return co(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const lq=10*1e3;function uq(e,t){if(!(t<60))return e*3600/t}function dq(e,t,n,r){let i=r-t;if(i<50||i>lq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function fq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=dq(t.input,t.atMs,n.input,n.atMs),i=dq(t.output,t.atMs,n.output,n.atMs),a=dq(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 pq(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>lq)continue;let o=dq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function mq(e){return HU(e.termCols??120)}function hq(e,t){return jo(Ao(e.claudeConfigDir,t))}function gq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function _q(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${k(t)}`),a=`${e}: ${String(t)}`}n.set(e,tt(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage(r)),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.getContextInfo(r)),c(`metrics`,()=>i.metricsProvider.getMetricsInfo(o,r)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(lt(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(hq(a,i.home)))])}function vq(e,t){let n=Gj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}const yq={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0,showPullRequest:!0};function bq({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,yq,t.workspace?.project_dir]}function xq(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${k(t)}`),Gj(L(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...bq(n))),tmux:i===null?Gj(I):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId))]))},faults:a}}function Sq(e){let{hookData:t,deps:n}=e,r=t.session_id,i=n.lanes(),a=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${k(t)}`),L(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:i.git.current(),usage:a(`session`,()=>n.usageStore.usageOf(r,t)),context:a(`context`,()=>n.contextProvider.contextOf(t)),metrics:a(`metrics`,()=>n.metricsProvider.metricsOf(r,t)),activity:a(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:i.tmux.current(),hostName:i.hostName.current(),hostUser:i.hostUser.current(),cache:a(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:a(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:a(`autocompact`,()=>n.autoCompact.stored(hq(e.hints,n.home))),sources:new Map([...i.sources].map(([e,t])=>[e,t.current()]))},today:a(`today`,()=>Cq(i.today,n.usageStore,r)),faults:rq.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function Cq(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function wq(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 Tq(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?so(t.why):void 0}const Eq=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function Dq(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=e.builtins,u={usage:Eq(l.session),context:Eq(l.context),metrics:Eq(l.metrics),activity:Eq(l.activity),cache:Eq(l.cache),speed:Eq(l.speed),autoCompact:Eq(l.autocompact),git:Eq(l.git),pr:Eq(l.pr),tmux:Eq(l.tmux),hostName:Eq(l.hostName),hostUser:Eq(l.hostUser)},d=(e,t)=>{switch(e.kind){case`pending`:return so(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},f=e=>e.kind===`ok`?e.value:void 0,p=i.tmux??null,m=u.git.kind===`pending`?so(u.git.why):u.git.kind===`ok`?Bq(u.git.value,u.pr,so):void 0,h=u.tmux.kind===`pending`?so(u.tmux.why):f(u.tmux)?.session,g=u.hostName.kind===`pending`?so(u.hostName.why):f(u.hostName),_=u.hostUser.kind===`pending`?so(u.hostUser.why):f(u.hostUser),v=Tq(u.context)??Fq(u.autoCompact,f(u.context)?.maxTokens),y=r.rate_limits?.five_hour,b=r.rate_limits?.seven_day,x=Tq(u.usage,u.metrics)??jq(f(u.usage)?.session.cost,f(u.metrics)?.sessionDuration),S=d(u.speed,Mq),C=d(u.usage,e=>Rq({cost:e.session.cost,tokens:e.session.tokens})),w=d(u.metrics,e=>Rq({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),T=d(u.activity,Iq),E=d(u.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),ee=d(u.cache,e=>({expiresAt:e})),D=zq(t.home),te=r.workspace?{...r.workspace,current_dir:zq(r.workspace.current_dir)??``,project_dir:zq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>zq(e)??e)}:r.workspace,O=r.session_id;return{...r,...te!==void 0&&{workspace:te},...D!==void 0&&{home:D},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:zq(r.location.main)??``}},...p!==null&&{tmux:{pane:p.pane,...h!==void 0&&{session:h}}},host:{...g!==void 0&&{name:g},..._!==void 0&&{user:_},...i.ssh!==void 0&&{ssh:i.ssh}},...oq(a),history:n.history,navigation:{back:n.back},term:{cols:mq(i)},...c,...s!==null&&{configPath:s},resumeCommand:nq(te,O,i.claudeConfigDir),...C!==void 0&&{session:C},...x!==void 0&&{burn:x},...S!==void 0&&{speed:S},...y!==void 0&&{block:{nativeUtilization:y.used_percentage,resetsAt:y.resets_at}},...b!==void 0&&{weekly:{percentage:b.used_percentage,resetsAt:b.resets_at}},...ee!==void 0&&{cache:ee},...E!==void 0&&{context:E},...w!==void 0&&{metrics:w},...T!==void 0&&{activity:T},...v!==void 0&&{autocompact:v},...Aq(Object.keys(e.sources),t=>{let n=Eq(e.sources[t]);return n.kind===`pending`?so(n.why):n})}}function Oq(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function kq(e){let t=Object.entries(e);return{runs:String(t.length),runsPending:t.flatMap(([e,{reading:t}])=>t.kind===`pending`?[`${Cn(e)}:${t.why}`]:[]).join(`,`)||`-`}}function Aq(e,t){let n=Object.fromEntries($S.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 jq(e,t){let n=e!=null&&t!=null?uq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Mq(e){let t=fq(e),n=pq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Nq(e,t){if(e.kind===`pending`)return so(e.why);if(e.kind!==`ok`)return;let n=tq(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function Pq(e,t,n){await _q(e,t,n),await Hj(()=>{let t=wq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Fq(e,t){switch(e.kind){case`pending`:return so(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return AI(e.value,t)}}function Iq(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=Lq(e.running),i=Lq(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 Lq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Rq(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 zq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Bq(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(UU(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:WU(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 Vq=Object.freeze({});function Hq(e,t){return e.kind===`decided`?t[e.name]??Vq:Vq}function Uq(e,t){return{...e,...Object.fromEntries(Zb.map(n=>[n,e[n]??t[n]]))}}const Wq=(e,t)=>bb(n=>{let{setting:r,on:i,inTmux:a}=pb[n].switch;return e[r]===i&&(t||!a)});function Gq(e,t,n,r){let i=Qb(e);return av(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function Kq(e,t){return Nx(t(`preset`),e.globals.preset,e.presets)}function qq(e,t,n){let r=Kq(e,t),i=Lx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Cte(a.palette,t(`theme`),i.palette),s=Uq(i,Hq(o,e.themeDefaults));return{...Object.fromEntries(Xb.map(e=>[e,Gq(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:_v(a.style,t(`style`),s.style,e.styles),effect:Dv(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function Jq(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const Yq={kind:`hidden`},Xq={kind:`shown`};function Zq(e,t){try{return Jq(e,t)?Xq:Yq}catch(e){let t=XC(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function Qq(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function $q(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function eJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function tJ({text:e,placement:t,lead:n,trail:r}){return{text:nJ(e),placement:t,...n!==void 0&&{lead:nJ(n)},...r!==void 0&&{trail:nJ(r)}}}function nJ(e){let t=e.blankCopy(e.plain);t.style=jP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(jP(i).clearMetaAndLinks(),n,r);return t}function rJ(e){let t=eJ(e);if(t.length===1)return e.text;let n=Qq(t);return n.style=e.text.style,n}function iJ(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=Qq(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:Qq([d,...c],a)},...l.length>0&&{trail:Qq([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:($q(u,n,p),[{text:u,...f}])}function aJ(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return mne(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 oJ(e,t){if(e.length===0)return 0;let{lines:n}=sF(e.map(({owner:e})=>e),t),r=B(ZP(n[n.length-1]));return Math.max(0,r-rF(t)+iF(t))}function sJ(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=sF([e],{...n,width:1/0});return B(ZP(r.flat()))<=n.width}function cJ(e,t,n,r){if(sJ(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=oJ(n,r);return i.divide(aJ(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 lJ(e,t){let n=Math.max(2,oF(t)-rF(t)-t.padding);return uJ(e,t).reduce((e,r)=>[...e,...cJ(r,n,e,t)],[])}function uJ(e,t){let n=()=>e.map(e=>({owner:rJ(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=sF(e.map(rJ),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(ZP(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];$q(c,c.cellLength+a,n)}),n()}function dJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=fJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:jP(a.style)};if(e.style.link){i();let r=fJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function fJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>pJ(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 pJ(e,t){let n=e.copy();return n.style=t,n}function mJ(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 hJ(e,t){let{look:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function gJ(e,t){let{layout:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function _J(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 vJ(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,yJ(e,t,o,n,r,i));return i}function yJ(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=Hx(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=ox.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=Hx(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=Hx(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:SJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:SJ(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:Gx(n),argv:n.run.map(n=>SJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,SJ(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:SJ(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 bJ(e){return e.kind===`do`?bJ(e.head):e}function xJ(e){switch(bJ(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 SJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function CJ(e,t){return e.has(t)?KC(e.read(t)):``}function wJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function TJ(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 EJ(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([jP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([jP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function DJ(e,t){return Math.max(e.members.indexOf(CJ(t,e.stateVar)),0)}function OJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:sS,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:sS,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:sS,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:sS,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:cS,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:lS,args:[i,wJ(e.text,_j(r))]}],active:!1};case`open`:return{effects:[{verb:uS,args:[i,wJ(e.target,_j(r))]}],active:!1};case`persist-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:fS,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:fS,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:fS,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:pS,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:vS,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:bS,args:[i]}],active:!1};case`redo`:return{effects:[{verb:xS,args:[i]}],active:!1};case`back`:return{effects:[{verb:SS,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:CS,args:[i]}],active:!1};case`save`:return{effects:[{verb:mS,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:hS,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:gS,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:_S,args:[i,wJ(e.name,_j(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:TS,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ES,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:DS,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:kS,args:[i,e.line]}],active:!1};case`run`:{let t=_j(r),n=JSON.stringify({run:e.argv.map(e=>wJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,wJ(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:yS,args:[i,e.key,QR(e.op)]}],active:!1};case`do`:{let o=OJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>OJ(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:yS,args:[i,e.key,QR(r)]}],active:!1}}}}function kJ(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:ia(`action "${e}"`,n,t.members.length,DJ(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 AJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=mJ(n,`action "${e}"`).store,{display:a,boundValue:o}=kJ(e,bJ(r),t,i),s=CJ(i,`session.id`),{effects:c,active:l}=OJ(r,a.plain,o,i,s,n.links.signer);return EJ(a,HS(n.links.to,c),l)}function jJ(e){return{action:{fn:(t,...n)=>AJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function MJ(e,t,n){return TJ(`✕`,HS(e,[{verb:sS,args:[CJ(t,`session.id`),n,ea]}]),!1)}function NJ(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(N_(e,t,n))})}function PJ({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function FJ(e,t,n){return new W({color:U.fromRgba(Iu(e.get(`warning`),t,M_,n))})}function IJ(e,t,n){return W.combine([NJ(e,t,n),FJ(e,t,n)])}function LJ(e,t,n){return PJ(G_(e.palette,e.disclosure,t,n))}function RJ(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(Fg.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const zJ=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},BJ=e=>new W({bold:e});function VJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>zJ(a,W.combine([LJ(e,{...n,distribution:t},i),BJ(o)]));let o=NJ(e.palette,a,i);return(e,t,i,a)=>HJ(i,W.combine([o,BJ(a)]),r(t,n))}const HJ=(e,t,n)=>zJ(q.fromFragments([zJ(e,t),zJ(` `,t),RJ(n)]));function UJ(e,t,n,r){return t===void 0?zJ(r):HJ(r,void 0,t(n,e))}function WJ(e,t,n,r,i){let a=NJ(e.palette,i,r);return(e,r,i,o)=>zJ(q.fromFragments([zJ(o?`[`:` `,a),RJ(n(r,t)),zJ(o?`]`:` `,a)]))}function GJ(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=>KJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function KJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function qJ(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function JJ(e){return{current:null,drawnAt:e}}function YJ(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 XJ(e,t,n){return QJ(e,()=>n(YJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function ZJ(e,t){return QJ(e,()=>(e.current=null,t()))}function QJ(e,t){let n=e.current;try{return t()}finally{e.current=n}}function $J(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 eY(e){return new q(e).cellLength}function tY(e){let{width:t,chromeCols:n,padding:r}=mJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function nY(e){let{padding:t,seamCols:n}=mJ(e,`a row fit`);return Math.max(1,tY(e)-(eY(`✕`)+2*t+n))}function rY(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 iY(e,t,n){let r=eY(`←`)+1+eY(`→`)+1,i=rY(e,t,n);return(i.length>1?rY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function aY(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 oY(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 sY(e,t,n){let r=e.compiled.get(t),i=r&&bJ(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 cY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=mJ(a,`picker`).store,d=CJ(u,`session.id`),f=`stateVar`in t?CJ(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`?nY(a):tY(a):1/0,h=(r.kind===`led`?0:eY(`✕`)+1)+c.reduce((e,t)=>e+eY(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?iY(v.map(e=>e.cellLength),m,h):GJ(g.entries,g.groups,i),b=parseInt(CJ(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>HS(a.links.to,[{verb:sS,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:sS,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ee=r.kind===`own`&&r.onPick?E:[],D=e=>HS(a.links.to,[...OJ(l,e,e,u,d,a.links.signer).effects,...ee]),te=(e,n)=>EJ(e,D(t.options[n])),O=r.kind===`led`?[]:[TJ(`✕`,HS(a.links.to,E),!1,s)];O.push(...c.map(({glyph:e,option:r})=>TJ(e,HS(a.links.to,[...OJ(l,r,r,u,d,a.links.signer).effects,{verb:sS,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&O.push(TJ(`←`,T(C-1),!1));let k=C<y.length-1?[TJ(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[aY([...O,...e.map(e=>te(v[e],e)),...k])]}let ne=new W({bold:!0}),A=y.length>1?` ${C+1}/${y.length}`:``,re=w.length===1?[new q(`${w[0].label}${A}`,{style:ne})]:[],ie=[aY([...O,...re,...k])];for(let e of w){w.length>1&&ie.push(aY([new q(e.label,{style:ne})]));let n=Math.max(...e.indices.map(e=>eY(_(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:VP(i),o=` `.repeat(n-eY(e)+2),s=a===void 0?e:`${e}${o}${a}`;ie.push(aY([te(p(r,qJ(s,m)),r)]))}}return ie}function lY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ZA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=oY(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=sY(e,n,`picker`),u=$J(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=>cY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,VJ(u,__(void 0),hJ(e,`{{ picker }}`),l.paletteOf,d,t),FJ(u.palette,t,d)),p=U_(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 uY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function dY(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=mJ(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=CJ(a,`session.id`),{options:c}=t;if(c.length===0)return aY([]);let l=uY(c,CJ(a,t.stateVar)),u=e=>c[l(e)],d=e=>HS(i.links.to,OJ(o,u(e),u(e),a,s,i.links.signer).effects);return aY([TJ(`◀`,d(-1),!1),EJ(UJ(hJ(i,`{{ carousel }}`),t.paletteOf,u(0),r),HS(i.links.to,OJ(i.compiled.get(n),u(0),void 0,a,s,i.links.signer).effects)),TJ(`▶`,d(1),!1)])}function fY(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(xJ(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 dY(t,sY(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function pY(e,t,n){let r=sY(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 mY(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 hY(e,t,n,r){let i=pY(e,t,n),a=r??CJ(mJ(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,hJ(e,`{{ ${n} }}`))}function gY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ZA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return RJ(hY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function _Y(e,t,n){return{swatches:{fn:(r,i)=>{let a=pY(e,r,`swatches`),o=oY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=$J(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]=cY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,WJ(s,hJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),FJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=uY(l,CJ(mJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[mY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const vY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function yY(e,t,n,r){let i=U_(e,n,r),a=(t,n)=>({text:t,colour:n,ink:N_(e,n,r)});return[[r_(e,t,r).map((n,i)=>{let a=j_(e,n);return{text:vY[i%vY.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 bY(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:PJ({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 xY(e,t,n,r,i){let a=yY(e,t,n,r).map(e=>bY(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
|
|
204
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function SY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ZA(`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}=hJ(e,`{{ themePreview }}`);return xY(r===void 0?a:hY(e,r,`themePreview`),o,{...$J(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),nY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const CY=e=>e.slice(e.lastIndexOf(`.`)+1),wY=(e,t)=>{let n=new q(CY(e));return n.truncate(t,{marker:`…`}),n.plain};function TY(e,t){let n=e.map(e=>e.map(({name:e})=>eY(CY(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 EY(e,t,n,r){let i=TY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new q(` ${wY(s,i)} `,{style:PJ(tv(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(`
|
|
205
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const DY=`layoutPreview`;function OY(e,t){return{[DY]:{fn:()=>EY(gJ(e,`{{ layoutPreview }}`),hJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),nY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function kY(e,t,n,r){let i=$J(r.activeSegment,`{{ menu }}`),a=r.action,o=HM(i.placementId,e,n.key),s=GM(o),c=VM(e),l=mJ(a,`menu`).store,u=CJ(l,o)===c,d=CJ(l,`session.id`),f=u?ea:c,p=TJ(ia(`{{ menu "${e}" }}`,t,2,+!!u),HS(a.links.to,[{verb:sS,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=U_(i.palette,i.disclosure,t).plane,l=sY(a,e,`menu`);return cY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,ea],[s,`0`]],onPick:n.closeOnPick},n.paged,a,VJ(i,n.distribution,hJ(a,`{{ menu }}`),l.paletteOf,t,c),FJ(i.palette,c,t))})():[]),p}const AY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jY(e,t){let n=t[t.length-1],r=AY(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:YM(r??{})}}function MY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=jY(t,n);return kY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function NY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=PY(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 PY(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 FY(e){let t={fn:(()=>{let t=$J(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:(()=>$J(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=$J(e,`{{ roleTextOn }}`);return RY(r,t,wu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=$J(e,`{{ keptOn }}`),i=wu(r,t),a=wu(r,n),o=ul(Ru(i,H.TRUECOLOR),Ru(a,H.TRUECOLOR)),s=Math.min(M_,Math.max(o,3));return(Lu(i,e.drawnAt(),(e,t)=>ul(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=MA(()=>$J(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...zY(s)];return NY({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 IY={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},LY=Object.values(IY).flat();function RY(e,t,n){let r=Ru(n,H.TRUECOLOR),i=t=>{let n=wu(e,t);return{colour:n,ratio:ul(Ru(n,H.TRUECOLOR),r)}},a=Fu(r).hex,o=IY[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,...LY.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 zY(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}const BY={input:`view`,state:`view`,template:`view`,time:`view`,shell:`view`,file:`view`,literal:`directory`,dropped:`directory`,source:`view`},VY=new WeakMap;function HY(e){let t=VY.get(e);return t===void 0&&(t=new Map([...IC(e)].map(([e,t])=>[e,BY[t.kind]])),VY.set(e,t)),t}function UY(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
206
|
+
`)){n.push(r);continue}let e=r.split(`
|
|
207
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function WY(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 GY=e=>e.kind===`failed`?Yq:e;function KY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function qY(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 JY(e){return{...e,cells:e.cells.map(tJ)}}function YY(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,...XY(e,r)]}function XY(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 ZY(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:YY(e.direction,e.children.map((t,i)=>n(t,[...r,QY(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function QY(e,t){return e.steps[t]}function $Y(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=eX(e);return{width:tX(t),reach:nX(t)}}function eX(e){let t=e.children.map($Y),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 tX=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),nX=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function rX(e,t){let n=eX(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=Kv[e.direction],i=__(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),nX(n),tX(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const iX={compile(e,t){let n=rX(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Qv(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),YY(e.direction,e.children.map((n,r)=>t.renderChild(n,GY(t.gate),QY(e,r))))}},aX={drop:e=>e.place,above:()=>`above`},oX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},sX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:qv(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(sa(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,$v(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,cX(e,t))};function cX(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=yj(t.scope,e.settings);if(t.gate.kind===`failed`)return mX(e,r,t,t.gate.message);try{let i=t.placement(e),a=KY(t.gate,i.gate());if(a.kind===`failed`)return mX(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 mX(e,r,t,s.message);let c=fx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:mP(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`?lX(f.variable):uX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?dX(p.segment,u):fX(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:Yq,h.disclosure).map(e=>({...e,place:aX[v.placement](e)})),b=(e,t,n)=>iJ(dJ([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?oX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new q(` `.repeat(pX(eJ(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],E=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),ee=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ee.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(eJ)),[...ee,...E]}catch(n){return mX(e,r,t,n.message??String(n))}}const lX=e=>({kind:`waiting`,variable:e});function uX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=XC(e);if(t===void 0)throw e;return lX(t.variable)}}function dX(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:UY(dJ(r,c)).map((e,t)=>({cells:iJ(e,{...l,lead:t===0?dJ(i,c):[],trail:t===0?dJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:iJ(dJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function fX(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=dJ(hX(e.lead,e,t,n),l),d=dJ(hX(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 iJ(dJ([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function pX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function mX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:iJ([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:mP(n.palette)},lead:hX(e.lead,e,t,n),trail:hX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function hX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=XC(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const gX={container:iX,segment:sX};function _X(e){return gX[e]}var vX=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?yX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const yX={kind:`hidden`},bX={palette:`theme`,style:`style`,effect:`effect`},xX=ox.get(`colorCompatibility`),SX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function CX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function wX(e){if(e.ok)return e.value;throw e.error}const TX=e=>({read:()=>e}),EX=Ng({basePalette:Mg,palette:Mg,decor:J_});var DX=class{evaluated=0;memory=new vX;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&EX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=_j(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(xX);return e.kind===`found`&&typeof e.value==`string`&&Mv(e.value)?e.value:`truecolor`});let i=(0,X.observable)(SX,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 ZY(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=BR(e);return i===void 0?[]:[{name:i,address:n,palette:fx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Nv(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=LM(e);return t===void 0?FM(e)===void 0?wM(this.view.get().payload(),e):wM(this.projected,e):CM(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()[bX[e]];if(t.kind===`decided`)return AX(t.name,null,null);let r=MX(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=NX(this.source,e,i.name,r.where,e=>{t=e}),AX(n,t,null)}case`pending`:return AX(n??yv[e],null,i.variable);case`failed`:return n=yv[e],AX(n,bv(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!jX(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)??yv[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return Zq(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>ZJ(this.source.activeSegment,()=>Zq(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new PX(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:_J(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=XC(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:CX(e)}),wX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:BR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function OX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new DX(t,n,e,r);return e.views.set(t,a),a}function kX(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 AX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),jX=(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 MX(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 NX(e,t,n,r,i){switch(t){case`palette`:return gx(n,r,i).name;case`style`:return gv(n,e.styles).name;case`effect`:return Ev(n).name}}var PX=class{where=FX(Ng({palette:Mg,region:K_}));ground=FX(Ng({colours:LX,bodyOpen:Mg}));opened=FX(Ng({colours:LX,open:Mg}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=yj(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?TX(Xq):e.derive(`${t.id} when`,e.readsInstant(a),()=>ZJ(r,()=>Zq(a,i))),this.open=d===void 0?TX(Yq):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>ZJ(r,()=>Zq(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return BX(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 VX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?TX(UX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return HX(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}),GX(n,r,this.affixes.read())}};function FX(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const IX=(e,t)=>e.hex===t.hex,LX=Ng({palette:Mg,drawnAt:Mg,tint:IX,text:IX,bg:IX,disclosure:Y_});function RX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const zX=e=>U_(e.palette,e.disclosure,e.drawnAt);function BX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...tv(n,r,i)};return XJ(e,RX(t,c),e=>{let t=Rte(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function VX(e,t,n,r,i,a){return XJ(e,RX(t,n),e=>(e.bg=i?zX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function HX(e,t,n,r,i,a,o){return XJ(e,RX(t,n),e=>(e.bg=r?zX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const UX={lead:[],trail:[],drops:[]};function WX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return NJ(t,zX(e).state,n)},get band(){return NJ(t,zX(e).plane,n)},get close(){return IJ(t,zX(e).state,n)},disclosure:r}}function GX(e,t,n){return{styles:WX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function KX(e,t,n,r,i,a,o){let s=BX(e,t,n,r,i,void 0,void 0,o);return GX(s,VX(e,t,s,a,!1,o),UX)}function qX(e,t,n,r,i){return WX(BX(e,t,n,r,i,void 0,void 0,{}))}function JX(e,t){return{payload:()=>e,selections:()=>t}}function YX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yM(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 XX(e,t){switch(ny(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 ZX(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:YX(n.cache),parse:XX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:YX(n.cache),parse:XX(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 QX(e,t,n,r=Rw.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 $X(e,t,n){let{compiled:r,loadWarnings:i}=tZ(e,t,n.cwd,eZ(n.links),aZ);return{...r,loadWarnings:i}}const eZ=e=>(t,n)=>oZ(n,e);function tZ(e,t,n,r,i=aZ){let a=nZ(e),o=rZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:iZ(e,t,n,i)}}function nZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of sx)n in t&&r.set(e,n);for(let[t,n]of ly(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...DG(e)].sort(([e],[t])=>e<t?-1:1)}}function rZ(e){return ce(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function iZ(e,t,n,r){let i=HY(e),a=DG(e),o=[];for(let[s,c]of IC(e))if(r.has(i.get(s)))try{ZX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const aZ=new Set([`directory`,`view`]);function oZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,links:r},a=()=>mJ(i,`drawnAt`).registry.drawnAt(),o=JJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Mx(e.presets),u=kR(e),d=[e=>_Y(i,o,e.now)],f=gj({extraFuncs:{...jJ(i),...gY(i),...lY(i,o),...fY(i),...SY(i,o),...OY(i,o),...MY(s),...FY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=QX(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=vJ(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:QX(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=py(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>yy(t,e,a,t=>String(mJ(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 _X(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Fx(e,t);C.set(t,S(n,r,void 0))}let w=new Map(dv.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of kG(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:lZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),E={reads:bG({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:hj(d)},ee=MG(E),D=[...C.values()].flatMap(cZ(y)).some(e=>ee(m.get(e))),te=D?new Set([...E.clock,DY]):E.clock,O=MG({...E,clock:te}),k=new Set([...m].flatMap(([e,t])=>O(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=MG({reads:bG({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:E.projections,clock:te});for(let e of yH){let n=y[t][e];n!==void 0&&r(m.get(n))&&k.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,links:r,globalExpressions:w,instant:k,layoutReadsInstant:D,styles:e.styles,runtime:i,views:new WeakMap}}function sZ(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 cZ=e=>t=>{let n=[];return ZY(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 lZ(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 uZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function dZ(e,t,n,r,i){let a=fZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function fZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??yv[e];case`failed`:return r({kind:`rule`,slot:e,message:bv(t.where,e,`the rule failed — ${n.error}`)}),yv[e]}}function pZ(e){return mZ(e).filter(e=>!e.name.startsWith(Zx)).map(e=>e.id)}function mZ(e){return e.kind===`container`?e.children.flatMap(mZ):[e,...e.opens===void 0?[]:mZ(e.opens.body)]}function hZ(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return OX(e,t,n,JX(o,a)),o}function gZ(e,t,n,r,i,a,o,s,c){try{var l=uo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new LP(``),h=m.clockAt(a,Sv[c.animationSpeed]),g=l.u(aj(a,h.timeline)),_=kX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:rF(v),padding:v.padding,seamCols:iF(v),preset:c.preset},i);let y=_.evaluated;l.u(_J(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:t_[c.variation],shade:Kg[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,qY),T=_.memory.from(C),E=new Set,ee={held:e=>T?.rules.get(e),waited:e=>E.add(e),settled:w.rule},D=new Map,te=e=>{let n=_.slot(e);if(D.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&&E.add(n.waited),n.name;let r=NX(t,e,dZ(e,n.rule,_,p,ee),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:O,style:k,effect:ne}=_.selections(),A=O.kind===`decided`?O:gx(te(`palette`),``,uZ),re=k.kind===`decided`?k:gv(te(`style`),e.styles),ie=ne.kind===`decided`?ne:Ev(te(`effect`)),ae=A.value,oe=mx(ae,re.value);_.publishLook({basePalette:ae,palette:oe,decor:S});let se=oe.get(`warning`),ce=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:se,text:N_(oe,se,r.drawnAt())},le=m.motion(ie.value,h,{transitions:x,source:C,last:T,returned:qY,hold:JY},ce);u?.clear();let ue=t=>e.segments[t],de=(e,i,a)=>{let o=i.kind===`hidden`?i:KY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${pZ(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:oe,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>KX(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:ue,renderChild:(e,t,n)=>de(e,t,$_(a,n)),renderBody:(e,t,n)=>de(e,t,ev(n)),closeDisclosure:e=>MJ(t.links.to,n,e),placed:(e,t)=>w.placed(e,le.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>E.add(e),decorations:(e,n)=>qX(t.activeSegment,e,n,a,r.drawnAt())};return _X(e.kind).render(e,c)},fe=t.roots.get(b);if(fe===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${jx}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let pe=WY(de(fe,Xq,Q_(S))).map(({line:e,row:t})=>{let n=lJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...sF(n.map(e=>e.owner),v,le.row(t,r,n))}});le.drawn(),w.commit();let me=()=>pe.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||mZ(fe).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),he=Math.min(g.heard(),...pe.map(e=>e.nextChange)),ge=Number.isFinite(he)?`moves`:me()?`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:pe.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:he,motion:ge,pending:[...E].sort()},evaluated:_.evaluated-y,cellBreaks:pe.reduce((e,t)=>e+t.cellBreaks,0),rules:D}}catch(e){l.e=e}finally{l.d()}}function _Z(e){return Wq(e.effective(),e.payload().tmux!==void 0)}function vZ(e,t,n,r,i,a,o,s){let{drawing:c,feeds:l,diagnostics:u}=t,{source:d}=e,f=d.effective(),p=d.payload().term.cols,m=gZ(e.state.config,e.state.compiled,e.store,e.registry,{diagnostics:TU(u),drawing:c,feeds:l,today:Nq(d.facts().builtins.today,n)},n,aq(f,p),{perSegmentSink:e.lastRenderCellsBySegment,onRenderWarning:s},{...f,effects:r,idleSince:i}),h=_Z(d),g={width:p,rows:DU(d.hints().termRows,c.by===`feed`?mb.flatMap(e=>{let t=pb[e].rows;return h[e]&&t!==null?[t]:[]}):[]),colorCompatibility:m.frame.depth},_=EU(a,u);return{...m,body:_===null?m.frame:WP(m.frame,OU(u,_,o,e.sessionId,c.by,g)),viewing:_,geometry:g}}const yZ={moving:1e3/30,still:1e3},bZ=[`data`,`state`,`reload`,`visibility`];function xZ(e){return mb.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 SZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const CZ=(e,t)=>pb[t].handsOff?e.resp:e.statusline,wZ=e=>Math.round(1e3/e);var TZ=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)??this.open(e),i={lane:this.laneOf(r,t.lane),sent:null};return r.followers.set(t,i),this.send(t,i),this.hasten(r),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(r,t)}laneOf(e,t){let n=e.lanes.get(t);if(n!==void 0)return n;let r=this.deps.encoders[t](),i={rate:[],encode:r,out:e.last===null?null:r(e.last.bar,CZ(e.last.answers,t))};return e.lanes.set(t,i),i}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 xb;let r=t-1,i=this.shown(n);return bb(e=>{let a=n.lanes.get(e)?.rate;if(a===void 0)return vb;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,lanes: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.lanes.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: ${k(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,wZ(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)},a=[...e.lanes].map(([e,n])=>({held:n,out:n.encode(t.bar,CZ(i,e))}));if(!(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline&&a.every(({held:e,out:t})=>e.out?.json===t.json))){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{held:e,out:t}of a)e.out?.json!==t.json&&SZ(e.rate,n),e.out=t;for(let[t,n]of e.followers)this.send(t,n)}}send(e,t){let{out:n}=t.lane;n===null||t.sent===n.json||(e.frame(n),t.sent=n.json)}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:pN(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=Zj.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=${wZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${bZ.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}};const EZ=`click.error`;function DZ(e,t,n,r){let i=kZ(e,t).filter(e=>at(e,5,r,`request`)!==`over`);NZ(e,t,{newest:{text:n,at:r,answered:!1},earlier:i})}function OZ(e,t,n){let r=PZ(e,t);if(r===null)return;let i=e=>n.some(t=>ot(e,t))?{...e,answered:!0}:e,a={newest:i(r.newest),earlier:r.earlier.map(i)};a.newest===r.newest&&a.earlier.every((e,t)=>e===r.earlier[t])||NZ(e,t,a)}function kZ(e,t){let n=PZ(e,t);return n===null?[]:[...n.earlier,n.newest]}function AZ(e,t,n,r){return kZ(e,t).map(e=>({error:e,hold:at(e,5,n,r)}))}const jZ=e=>e.flatMap(({error:e,hold:t})=>t===`over`?[]:[e]),MZ=e=>jZ(e).filter(e=>!e.answered);function NZ(e,t,{newest:n,earlier:r}){e.set(t,EZ,JSON.stringify({...n,earlier:r}))}function PZ(e,t){let n=e.get(t,EZ);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return null}let i=FZ(r);if(i===null)return null;let{earlier:a}=r;return{newest:i,earlier:Array.isArray(a)?a.flatMap(e=>{let t=FZ(e);return t===null?[]:[t]}):[]}}function FZ(e){if(typeof e!=`object`||!e)return null;let{text:t,at:n,answered:r}=e;return typeof t==`string`&&typeof n==`number`&&(r===void 0||typeof r==`boolean`)?{text:t,at:n,answered:r===!0}:null}function IZ(e,t){return mb.filter(n=>e[n]&&pb[n].handsOff&&t.has(n))}function LZ(e,t,n){return{severity:pU,lines:[[mU(`[⟲ claude]`,HS(e,[{verb:vS,args:[t,...n.map(e=>pb[e].switch.setting)]}]))]]}}function RZ(e,t){for(let n of Object.entries(t))e.push(n)}const zZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function BZ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,k(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function VZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...BZ(n)];return{level:zZ[n.kind],line:HZ(e,i)}}const HZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function UZ(e,t,n){if(t.kind===`pending`)return so(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}const WZ=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`]),GZ=[[`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`]],KZ=[[`workspace.added_dirs`,`string-list`]];function qZ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of GZ){let i=XZ(n,e);if(i==null)t.missingRequired.push(e);else{let n=JZ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of KZ){let i=XZ(n,e),a=i===void 0?r:YZ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))WZ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function JZ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function YZ(e){return Array.isArray(e)&&e.every(e=>JZ(e)===`string`)?`string-list`:JZ(e)}function XZ(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 ZZ(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 QZ(e){let t=ZZ(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}new Set(rq);function $Z(e){return{hookData:e.hookData,cwd:e.cwd,hints:e.hints}}function eQ(e){let t=e.kind===`recording`?{kind:e.kind,v:6,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,at:e.at,drawing:e.drawing,feeds:e.feeds,state:{...e.state,idleSince:e.state.idleSince??null},diagnostics:e.diagnostics}:e.kind===`turn`?{kind:e.kind,held:e.held,at:e.document.at,facts:e.document.facts,...$Z(e.request),state:e.state}:{kind:e.kind,...e.kind===`request`&&{at:e.at},...$Z(e.request)};return`${JSON.stringify(t)}\n`}function tQ(e,t){let n=new Map,r=!1,i=e=>{for(let t of e.watching)t();e.watching.clear()},a=(e,t,r)=>{let a=n.get(e);a===void 0||!a.delete(t)||(a.size===0&&n.delete(e),i(t),t.sink.end(r))},o=(e,n,r)=>{if(!(r.kind===`facts`&&r.facts===n.document)&&!(r.kind===`declared`&&r.request===n.declaration))try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),r.kind===`turn`&&(n.document=r.document.facts),(r.kind===`request`||r.kind===`declared`||r.kind===`turn`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${k(r)}`),a(e,n,{kind:`failed`,error:r})}},s=(e,t,n)=>{let r=n.source.held();t.turn?.view===n&&t.turn.held===r||(t.turn={view:n,held:r},o(e,t,{kind:`turn`,held:r,...n.source.turn()}))},c=(t,r,i,{view:a,state:c,drawing:l,feeds:u,diagnostics:d})=>{let f=e.sessionView(t),p={at:i,drawing:l,feeds:u,state:c,diagnostics:d},m=[()=>s(t,r,a),()=>o(t,r,{kind:`facts`,...a.followed.stamped()}),()=>o(t,r,{kind:`declared`,request:a.facts()}),()=>o(t,r,{kind:`draw`,...p}),...f===null?[]:[()=>s(t,r,f)]];for(let e of m)n.get(t)?.has(r)&&e()},l=(t,r)=>{let i=e.sessionView(t);if(i===null)return;let a=(e,i)=>{if(!n.get(t)?.has(r))return;let a=(0,X.reaction)(e,i,{fireImmediately:!0});n.get(t)?.has(r)?r.watching.add(a):a()};a(()=>i.source.held(),()=>s(t,r,i)),a(()=>i.followed.stamped(),e=>o(t,r,{kind:`facts`,...e}))};return{record(t,i){if(r)throw Error(`the daemon is closing: it records nothing more`);let s=e.sessionView(t);if(s===null)throw Error(`no view of session ${JSON.stringify(t)} is open in this daemon: it has not drawn a bar here since the daemon started, or its view closed while it was idle`);let c={sink:i,watching:new Set,document:null,declaration:null,turn:null},u=n.get(t)??new Set;return n.set(t,u.add(c)),o(t,c,{kind:`recording`,session:t,home:s.source.home()}),u.has(c)&&l(t,c),()=>a(t,c,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])i(t),l(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])o(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(e,{at:t,noted:r},i){let a=[...n.get(e)??[]].filter(e=>r.has(e));if(a.length===0)return;let o=i();for(let n of a)c(e,n,t,o)},fed(e,t,r){let i=[...n.get(e)??[]];if(i.length===0)return;let a=r();for(let n of i)c(e,n,t,a)},close(){r=!0;for(let[e,t]of n)for(let n of t)a(e,n,{kind:`closed`})}}}function nQ(e,t){let n=null,r=tQ({sessionView:e=>{if(n===null)throw Error(`a recorder read its cache before the cache was built`);return n.sessionView(e)}},t);return n=e({onSessionViewMoved:e=>r.moved(e)}),{cache:n,recorder:r}}function rQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}const iQ=(e,t)=>({view:e,state:{...e.source.state(),idleSince:t.idleSince},...t.handed});function aQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,()=>iQ(t,i)),i}function oQ(e,t,n,r){let i=r();return e.fed(t.sessionId,n,()=>iQ(t,i)),i}var sQ=class extends Error{name=`RecordingFailed`};function cQ(e,t,n,r,i,a){return new Promise((o,s)=>{let c;try{c=C(r,`wx`,384)}catch(e){s(Error(e.code===`EEXIST`?`${r} already exists: a recording writes a new file`:`${r} cannot be created: ${String(e)}`));return}let l=0,u={request:0,feed:0},d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{g(c,eQ(e)),l++,e.kind===`draw`&&u[e.drawing.by]++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{_(c),u.request+u.feed===0&&D(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u.request,frames:u.feed,daemonClosed:e.kind===`closed`}):s(new sQ(`writing ${r}: ${String(t)}`))}};a.addEventListener(`abort`,p,{once:!0});try{d=e.record(n,m)}catch(e){a.removeEventListener(`abort`,p),f(),_(c),D(r),s(e)}})}const lQ=()=>{},uQ=e=>({ok:!1,error:e instanceof Error?e.message:k(e),code:`RENDER_FAILED`,daemonV:3}),dQ={ansi:e=>({ok:!0,output:cne(e)}),frame:e=>({ok:!0,frame:e})};function fQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=uo();let i=c.u(yQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=oQ(e.recorder,i.view,r,()=>xQ(e,i,{by:`feed`,fps:n})),p=dQ.ansi(o.body),m=DQ(e.links.to,t,o,IZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:dQ.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}=VZ(`render`,s,{kind:`threw`,error:e},tt(i,o)),r=uQ(e);return{bar:nne(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:lQ,failure:{level:t,line:`frame ${n}`}}}}function pQ(e,t,n){let{sessionState:r}=e;return qq(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function mQ(e,t){try{var n=uo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:Wq(i.view.source.effective(),gc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function hQ(e,t,n){let r=e.frameFeeds.latest(n);return gQ(e,t,n,r===null||gc(r.hints.tmux))}function gQ(e,t,n,r){try{var i=uo();return Wq(pQ(e,n,i.u(e.renderCache.hold(t.projectDir,t.cwd,t.target.path)).state),r)}catch(e){i.e=e}finally{i.d()}}function _Q(e,t,n,r){RZ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=br(e,i),o=xr(a);return RZ(n,{termCols:String(i.termCols??`?`),termRows:String(i.termRows??`?`),refused:a.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:i.client?.kind??`unreported`,rateLimits:e.rateLimits}),o}function vQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&s.isAbsolute(a)&&{location:fc(a)}}},c=_Q(o,n,r,e.rendererName);RZ(r,{encoding:o.encoding});let l=o.requested;return bQ(i.holdSession(l.projectDir,l.cwd,l.target.path,o),o,c,n,r)}function yQ(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=_Q(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return bQ(a,o,s,n,r)}function bQ(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c}=t;return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function xQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkIds:s,links:c,fileEvents:l,renderWarnings:u,payloadProviders:d,effectSessions:f,menuIdle:p,launcher:m}=e,{req:h,at:g,facts:_,sessionId:v,entry:y,state:b,view:x,hintsError:S}=t,C=x.source.payload(),w=x.source.effective(),T=x.source.failure(),E=_Z(x.source);RZ(_,{lanes:mb.filter(e=>E[e]).join(`,`)||`-`}),RZ(_,{width:String(C.term.cols)});let ee=AZ(r,v,g,n.by),D=o.notice({to:c.to,sessionId:v,dismissed:r.get(v,Az),enabled:w.updateNotice}),te=VU(y.repos,v,c),O=(e,t)=>({about:e,text:t,copy:t}),k=e=>O(e??``,e),ne=[k(Cr(h.refusedArgs)),k(S),O(`load`,y.lastError),O(`update-act`,o.error()),O(`link-ids`,s.error()),...b.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),...jZ(ee).map(e=>O(`click\0${e.at}\0${e.text}`,e.text))].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),A=y.watch===null?null:Ej(`config watch`,y.watch,null),re=m.launcherWarnings(g,n.by),ie=re.find(e=>e.kind===`launch-pipes`),ae=ie?.event??null,oe=[...jc(l.delivery()),...re,...A===null?[]:[{kind:`config-watch`,message:A}],...y.lastWarning===null?[]:[{kind:`load`,message:y.lastWarning}],...T===null?[]:[{kind:`facts`,message:T.cause===`inputs`?`the bar is held on the last turn taken: ${T.reason}`:`the bar is drawn from the last facts that were read; the next could not be stamped: ${T.reason}`}]],se={config:b.config},ce=hU(c.to,v,n.by,ne,[...D,...te],[...oe.map(e=>({about:e.kind,message:e.message})),...u.ofSession(v,n.by,se).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),le=x.source.facts(),ue={drawing:n,feeds:i.feedsOf(v,g),diagnostics:ce},de=co(C.metrics)?void 0:C.metrics;RZ(_,Oq(le.sources)),RZ(_,kq(le.runs)),RZ(_,{factsSeq:String(le.seq),prompts:String(de?.messageCount??`-`),nonPrompts:String(de?.nonPrompts??`-`),pr:cq(C.git),feeds:xZ(ue.feeds)});let fe=[],pe=f.of(v),{body:me,viewing:he,geometry:ge,evaluated:_e,cellBreaks:ve,rules:ye,idleSince:be}=p.drawn(v,g,w.menuTimeout,e=>vZ(x,ue,g,pe,e,r.get(v,iS),c.to,e=>fe.push(e))),xe=_U(ce),Se=new Map(ce.map((e,t)=>[xe[t],e.copy])),Ce=()=>a.delivered(v,n.by,Se),we=p.since(v,g);RZ(_,{menuIdle:we===void 0?`-`:`${(g-we).toFixed(1)}s/${w.menuTimeout}s`});let Te=u.drawn(v,n.by,se,fe),Ee=d.gitProvider.getStats(),De=d.usageStore.getStats(),Oe=pe.lastFrame(),ke=Oe.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,Ae=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=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}},Me=[...oe,...fe].map(je).join(`,`)||`-`;return RZ(_,{git:`${Ee.size}/${Ee.hits}h/${Ee.misses}m`,usage:`${De.size}/${De.hits}h/${De.misses}m`,effect:Oe.effect,effectT:Oe.t.toFixed(3),speed:`${Oe.speed}x`,effectRows:`${Oe.made}made/${Oe.reused}reused`,effectOwn:ke,fadeBasis:Oe.basis,stateRev:String(Oe.revision),fades:Ae(Oe.fades),leaves:Ae(Oe.leaves),motion:me.motion,evaluated:String(_e),cellBreaks:String(ve),pending:me.pending.join(`,`)||`-`,rules:[...ye].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ne.length>0?`Y`:`N`,clickError:ee.map(({hold:e})=>e).join(`,`)||`-`,pipeEvent:ie?.hold??`-`,upd:String(D.length),ask:String(te.length),warn:Me,diag:String(ce.length),warnRecord:Te?`new`:`kept`,viewer:he===null?`-`:`${he.index}/${ce.length}p${he.page+1}`}),{drawn:{body:me,viewerOpen:he!==null,diagnostics:ce,geometry:ge},evaluated:_e,cellBreaks:ve,answersClick:MZ(ee),pipeShown:ae,delivered:Ce,lanes:E,idleSince:be,handed:ue}}function SQ(e,t){let{laneSetups:n,tmuxStatusLines:r}=e,i=gQ(e,t.requested,t.sessionId,gc(t.hints.tmux));return r.observe(t.sessionId,t.hints.tmux,i.tmuxStatus),n.noted(t.sessionId,i)}function CQ(e,t,n){return aQ(e.recorder,t.view,n,()=>xQ(e,t,gb))}function wQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:cF(e.hookData)}}function TQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);return s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus),a.clicked(t,n,r)}async function EQ(e,t,n,r,i){try{var a=uo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(vQ(e,t,n,i)),u=rQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;RZ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Uj(e=>Promise.all([u.landed,l.view.registry.inFlight(e)]),f,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${k(e)}`),o.after),m=o.monotonic();RZ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:gq(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=CQ(e,l,u.arrival),b=t.sessionId,x=IZ(y,s.following(b)),S=lF(t.hints.client??null)===`statusline`,C=dQ[t.encoding](S?DQ(e.links.to,b,h,x):h.body);return RZ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${tt(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function DQ(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:WP(n.body,kU(LZ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const OQ=/^─{20,}/,kQ=/^❯(\s|$)/,AQ=/›\s*stashed$/;function jQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>OQ.test(e)?[t]:[]).at(-2);return n===void 0||!kQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function MQ(e){if(e.inMode)return{kind:`in-mode`};let t=jQ(e);return t===null?{kind:`no-prompt`}:AQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function NQ(e){return/^❯\s*\S/u.test(jQ(e)?.prompt??``)}const PQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function FQ(e){return e.screen.some(e=>PQ.test(e))}const IQ={"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 LQ(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 RQ(e,t,n){let r=MQ(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:IQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function zQ(e,t,n,r,i){let a=await Ws(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function BQ(e,t){let n=await zQ(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(`
|
|
208
|
+
`);return{inMode:r!==`0`,screen:i}}function VQ(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 HQ(e,t,n){let r=await zQ(e,t,`claude-input.type`,VQ(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 UQ(e){return{read:t=>BQ(e,t),type:(t,n)=>HQ(e,t,n)}}const WQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`,run:({run:e})=>`run:${e.action}`,"lane-setup":({lane:e,on:t})=>`lane-setup:${e}-${t?`on`:`off`}`,doctor:({step:e})=>`doctor:${e.kind}`};function GQ(e){let t=WQ[e.kind];return t(e)}const KQ=`render-origin`,qQ=`client-hints`;function JQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Iv:Lv;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const YQ=Object.entries(nx),XQ=new Set(ix.map(e=>e.sessionKey)),ZQ=()=>!1;function QQ(e,t){return qq(e,e=>XQ.has(e)?t(e):null,ZQ)}const $Q=[`preset`,`theme`];function e$(e,t,n){let r=new Set($Q.slice(0,n).map(e=>nx[e].sessionKey));return qq(e,e=>r.has(e)?t(e):null,ZQ)}function t$(e,t){let n=Array.from({length:$Q.length+1},(n,r)=>e$(e,t,r));return e=>{let t=$Q.indexOf(e);return n[t===-1?$Q.length:t]}}function n$(e,t,n,r){return e.flatMap(([e,i])=>{let a=JQ(t,e);return a===null||a===JQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function r$(e,t,n){return JQ(QQ(e,t),n)}function i$(e,t){let n=QQ(e,t);return n$(YQ,n,t$(e,t),t=>a$(e,n.preset,t.configKey))}function a$(e,t,n){return n in(Px(e.presets,t).globals??{})?qN(t,n):n}function o$(e,t,n){let r=Nx(t(nx.preset.sessionKey),e.globals.preset,e.presets),i=JN(n);return{key:i?.scope===`globals`?a$(e,r,i.field):n,globals:Lx(e,r)}}function s$(e,t){let{preset:n}=QQ(e,t);return u$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:vy(a,s);return c===void 0||_y(c)===_y(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function c$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Mx(e.presets).flatMap(n=>{let i=u$(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 hy(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:vy(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const l$=new WeakMap;function u$(e,t){let n=l$.get(e)??new Map;l$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Zv(Fx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=py(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 d$(e,t){let n=QQ(e,t);return{from:n.preset,globals:Px(e.presets,n.preset).globals??{},picks:n$(YQ.filter(([e])=>e!==`preset`),n,t$(e,t),e=>e.configKey),placements:s$(e,t)}}function f$(e,t){return qq({...e,globals:{palette:t},presets:{}},()=>null,ZQ)}function p$(e,t){let n=QQ(e,t),r=JQ(n,`theme`);if(r===null)return{kind:`rule`};let i=f$(e,r),a=Lx(e,n.preset),o=Object.fromEntries(Zb.map(e=>[e,JQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Zb.some(e=>o[e]!==JQ(i,e))}}function m$(e){return{sessionKeys:ix.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...TN(e)?YK.map(t=>qN(t,e)):[],...KN(e)?ov().map(t=>GN(t,e)):[]]}}function h$(e){return new Set(ix.map(e=>e.configKey).filter(t=>m$(t).fileKeys.some(t=>v$(e,_$(t)))))}function g$(e,t,n){let r=i$(e,n),i=new Set(r.map(e=>e.configKey)),a=cx(e=>i.has(nx[e].configKey)||t.has(nx[e].configKey)),o=p$(e,n);return{unsaved:r.length+s$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function _$(e){let t=JN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return YN(t)}function v$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&v$(e[n],r)}function y$(e,t,n){let r=lx.get(n);if(r!==void 0)return r$(e,t,r);for(let[,t]of ly(e))if(t.key===n)return t.default??null;return null}function b$(e,t){let n=zN(e).get(t);return n===void 0?null:String(n)}const x$={inside:()=>[],defaultOf:()=>ea,menus:[]},S$=e=>`${e.key}\0${e.member}`;function C$(e){let t=new Map,n=n=>{let r=`${n.name}\0${qv(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:iG(a,qv(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(S$(e))??new Map;n.set(S$(t),t),o.set(S$(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(S$(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 Mx(e.presets))d(Fx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ma(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(S$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(S$(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(S$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const w$=new WeakMap;function T$(e){let t=w$.get(e);if(t!==void 0)return t;let n=C$(e);return w$.set(e,n),n}function E$(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 D$(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 O$(e,t,n){let r=(r,i,a)=>{let o=E$(t(r),t=>e.get(r,t),i);(0,X.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),values:t=>e.values(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 k$=new Set([`1`,`true`]),A$=new Set([`0`,`false`,``]);function j$(e,t){let n=n1(e),r=n.scope===`segment-palette`?`string`:ex(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(k$.has(t))return`true`;if(A$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function M$(e){try{return h.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function N$(e,t,n){try{if(t===null){h.rmSync(or(Pn,e),{force:!0});return}dr(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function P$(e){return/^\s*$/.test(e)?null:wa(e)}function F$(e,t){return e!==null&&Ea(e,t)!==void 0}function I$(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(I$),...i}}return e}function L$(e){if(!bx(e))return I$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,I$(t)])),...n}}const R$=KK,z$=R$.segments,B$=R$.presets,V$=R$.root;function H$(e,t,n,r){if(!F$(e,t)&&n===void 0)throw new R(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function U$(e,t){let n=YN(t);return t.scope===`segment-palette`&&H$(e,[`segments`,t.segment],z$[t.segment],n.join(`.`)),n}function W$(e){return wa(Pa(e))}function G$(){return Object.entries(V$.rows).map(([e,t])=>{let n=I$(t);return{path:[`root`],fragment:W$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function K$(e,t){let n=e===null?void 0:Ea(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function q$(e,t){if(t===void 0)return null;let n=L$(t);return{path:e,fragment:W$(n),unit:{path:e,value:n}}}function J$(e,t){let n=[`presets`,t],r=[...n,`root`],i=B$[t];H$(e,n,i,r.join(`.`));let a=K$(e,r)??q$(r,i?.root);return a!==null&&eo(a.fragment)?a:null}function Y$(e,t){let n=$a(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 X$(e,t){return[...G$(),K$(e,[`root`]),J$(e,t)].filter(e=>e!==null).reduce(Y$,new Map)}function Z$(e,t,n){for(let{node:r,...i}of X$(e,t).values())if(no(r,n))return i;throw new R(`${Q$(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 Q$(e,t){return J$(e,t)?.path??[`root`]}function $$(e,t){return t.scope===`preset-root`?Q$(e,t.preset):YN(t)}function e1(e,{unit:t}){return t===null?e:qa(e,t.path,Pa(t.value),Ma)}function t1(e){let t=JN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function n1(e){let t=t1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function r1(e,t,n,r,i){let a=m1(t,r),o,s=()=>(o??={chain:c1(t,n)}).chain;h1(t,s,a),i(t,s,a),N$(t.path,r,e.logger),e.record(t.path,n,r)}function i1(e,t,n){let r=s1(e,t(),n);if(r.length>0)throw new R(`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 a1=()=>{};function o1(e,t){try{return t()}catch(t){throw!(t instanceof R)||e.above.length===0?t:new R(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function s1(e,t,n){if(t===null)return[];let r=new Set(f1(d1(t),d1(n)));return f1(u1(e,t),u1(e,n)).filter(e=>!r.has(e))}function c1(e,t){try{return l1(e,t)}catch(e){if(e instanceof Cy)return null;throw e}}function l1(e,t){return SK(e.locs,t===null?e.above:[$H(e.path),...e.above],JK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:h.readFileSync(n,`utf8`))}function u1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function d1(e){return e.layers.at(-1)?.config??e.base}function f1(e,t,n=``){return!p1(e)||!p1(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>f1(e[r],t[r],n===``?r:`${n}.${r}`))}function p1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function m1(e,t){try{return l1(e,t)}catch(e){throw e instanceof Cy?new R(`refused: the config file would not load after this click — ${e.message}`):e}}function h1(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 R(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new Cy(e,[t]).message).join(`
|
|
209
|
+
`)}`)}function g1(e,t){let n=n1(t),r=P$(M$(e)??``),i=r===null?void 0:Ea(r,YN(n));return i!==void 0&&`value`in i?i.value:void 0}function _1(e,t,n){v1(e,t,n,[])}function v1(e,t,n,r){let i=M$(t.path),a=n.reduce((e,[t,n])=>qa(e,U$(P$(e),n1(t)),j$(t,n),Ma),i??``);r1(e,t,i,o1(t,()=>y1(a,t.path,r,e=>e)),i1)}function y1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Z$(P$(s),n,i),l=aee(e1(s,c),c.path,i,a,Pa(o));if(l===null)throw new R(`${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 b1(e,t,n){let r=P$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of X$(r,t)){if(!no(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Oa(e,c):Pa(s.value);if(a!==`#`)return qa(e,[...i,`rows`,a],l,Ma);if(J$(r,t)!==null)throw new R(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return qa(e,i,l,Ma)}return e}function x1(e,t){return Ya(e,t,t[0]===`presets`&&t.length>2&&!XK(t[1])?2:0)}function S1(e,t,n){let r=n.map(t1),i=M$(t.path);if(i===null)return;let a=r.reduce((e,t)=>x1(e,$$(P$(e),t)),i);a!==i&&r1(e,t,i,a,a1)}function C1(e){let t=e===null?void 0:Ea(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function w1(e,t){let n=new Set([...YK,...C1(e),...t.above.flatMap(e=>Object.keys(ya.default.parse(h.readFileSync(e.path,`utf8`)).presets??{}))].map(BM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(BM(e)))}function T1(e,t,n,r,i,a){let o=M$(t.path),s=P$(o??``),c=w1(s,t),l=[`presets`,c],u=o1(t,()=>J$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Oa(o??``,u.fragment):Pa(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Pa(r)]]],f=i.map(([e,t])=>{let n=qN(c,e);return[U$(s,n1(n)),j$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>qa(e,t,n,Ma),qa(o??``,l,`{}`,Ma));return r1(e,t,o,o1(t,()=>y1(p,t.path,a.map(e=>({...e,preset:c})),b1)),i1),c}function E1(e,t,n,r){let i=M$(t.path);r1(e,t,i,qa(i??``,[`themeDefaults`,n],Pa(r),Ma),i1)}function D1(e,t,n){if(XK(n))throw new R(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=M$(t.path),a=P$(i??``);if(i===null||a===null||Ea(a,r)===void 0)throw new R(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ea(a,[`globals`,`preset`]);r1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>x1(e,t),i),a1)}function O1(e,t,n,r){let i=t1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=M$(t.path),o=r.op===`remove`?r.target:r.anchor,s=o1(t,()=>Z$(P$(a??``),i.preset,o)),c=e1(a??``,s),{after:l,placed:u}=k1(c,s.path,r,()=>{let e=m1(t,c).config;return Mx(e.presets).map(t=>Fx(e,t).node)});if(l===null)throw new R(`${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 r1(e,t,a,l,i1),u}function k1(e,t,n,r){switch(n.op){case`remove`:return{after:ree(e,t,n.target),placed:null};case`insert`:{let i=ez(n.segment,n.anchor,r());return{after:iee(e,t,i,n.anchor,n.relation),placed:i}}}}const A1={inTurn:()=>`single-run`};function j1(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),values:t=>e.values(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 M1={load:()=>({}),save:()=>{},flush:()=>{}};var N1=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e,t=M1,n=256){this.turns=e,this.maxSessions=n,this.storage=t,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).filter(([,e])=>Object.keys(e).length>0).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}values(e){return this.atom.reportObserved(),Object.fromEntries(this.sessions.get(e)?.values??[])}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){this.held(e),t.length!==0&&this.commit(e,e=>{t.some(({key:t,value:n})=>e.values.get(t)!==n)&&(e.revision=++this.head);for(let{key:n,value:r}of t)e.values.set(n,r)})}clear(e,t){this.held(e),this.commit(e,e=>{e.values.delete(t)&&(e.revision=++this.head)})}restore(e,t,n){this.held(e),(this.sessions.get(e)?.revision??0)!==n&&this.commit(e,e=>{e.values.clear();for(let[n,r]of Object.entries(t))e.values.set(n,r);e.revision=n,this.head=Math.max(this.head,n)})}commit(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t(n),n.values.size===0?this.sessions.delete(e):(this.touch(e,n),this.evictOldest()),this.persist(),this.atom.reportChanged()})}held(e){if(this.turns.inTurn()===null)throw Error(`session state: a write of ${JSON.stringify(e)} outside any turn`)}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=M1}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function P1(e){let t=new Map;return{dir:e.dir,onDisk:n=>{let r=t.get(n);if(r!==void 0)return r;let i=e.onDisk(n);return t.set(n,i),i}}}function F1(e,t){return z1(e.dir,t)??I1(e,t)}function I1(e,t){let n=e.onDisk(e.dir);for(let r of L1(t)){let i=R1(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function L1(e){let t=s.dirname(e);return t===e?[]:[t,...L1(t)]}function R1(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function z1(e,t){let n=R1(e,t);return n===``?null:n}function B1(e,t){let n=F1(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var V1=class extends Error{};function H1(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new V1(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return U1(e,t)}if(typeof t!=`object`||!t)throw new V1(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new V1(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||z1(e.dir,t)!==r)throw new V1(`stored home path ${JSON.stringify(r)} is not a plain path inside the home's root ${e.dir}`);return t}if(n===`world`){if(!s.isAbsolute(r))throw new V1(`stored world path ${JSON.stringify(r)} is not absolute`);if(z1(e.dir,r)!==null)throw new V1(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return U1(e,r)}throw new V1(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function U1(e,t){let n=F1(e,t);return n===null?t:s.join(e.dir,n)}const W1={load:()=>({}),save:()=>{}},G1=new Set(ix.map(e=>e.sessionKey)),K1=e=>G1.has(e)||e.startsWith(sP),q1=8*1024*1024,J1={past:[],future:[]},Y1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var X1=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=W1){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)??J1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??J1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(Y1(r));i.set(Y1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:j1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!K1(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:i0(i,r),o=n.get(e),s=o===void 0?a:c0(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 R(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,o0(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new R(`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(Y1)),a=n.net.filter(e=>!i.has(Y1(e))),o=$1(l0(s0(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new R(`rewind: ${r.map(d0).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 R(`redo: nothing to redo`);let a=[...n,i],o=$1(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...t0(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(Y1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:l0(n,t),future:l0(i,t),...a!==void 0&&{savepoint:{at:l0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(Y1(e))),below:l0(a.below,t)}}}),new R(`${r}: ${o.map(d0).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):M$(t.file)}write(e,t,n){t.kind===`file`?N$(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||Z1(n)>q1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,Q1(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${q1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function Z1(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 Q1({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...t0(n,1,[])}:{past:e,future:t.slice(1),...t0(n,0,[])}}function $1(e){return e.slice(-50)}const e0=e=>e===lP.member;function t0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:n0(e.net,n),below:e.below}}}function n0(e,t){let n=new Map(e.map(e=>[Y1(e),e]));for(let e of t){let t=n.get(Y1(e));n.set(Y1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const r0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function i0(e,t){let n=[...e.past,t],r=$1(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...t0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...a0(e.future,a),...i.below]},n.length-r.length,t)}}function a0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function o0(e,t){return{past:e.past.slice(0,-1),future:$1([...e.future,t]),...t0(e.savepoint,0,r0(t))}}function s0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...a0(r,t.at-i.length),...t.below]}function c0(e,t){if(e0(t.after)&&!e0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!e0(t.after)&&e0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function l0(e,t){return e.map(e=>e.filter(e=>!t.has(Y1(e)))).filter(e=>e.length>0)}function u0(e){return e.map(d0).join(`, `)}function d0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function f0(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`&&`file`in t)&&n(t.before)&&n(t.after)}function p0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(f0))}function m0(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(f0)&&p0(t.below)}function h0(e){if(typeof e!=`object`||!e)return!1;let t=e;return p0(t.past)&&p0(t.future)&&(t.savepoint===void 0||m0(t.savepoint))}function g0(e,t){let n=e=>e.kind===`file`||K1(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 _0(e,t){let n=(e,n)=>e.map(e=>e.kind===`file`?{...e,file:t(e.file,n)}:e),r=(e,t)=>e.map((e,r)=>n(e,`${t} step ${r+1}`)),{past:i,future:a,savepoint:o}=e;return{past:r(i,`undo`),future:r(a,`redo`),...o!==void 0&&{savepoint:{at:o.at,net:n(o.net,`edit mode's change`),below:r(o.below,`edit mode's redo`)}}}}function v0(e,t,n){return{load:()=>{let r;try{r=h.readFileSync(e,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&n(`warn`,`settings-history read failed (${t}); starting empty`),{}}let i;try{i=JSON.parse(r)}catch{i=null}if(typeof i!=`object`||!i||Array.isArray(i)||!Object.values(i).every(h0))return n(`warn`,`settings-history load: unexpected shape, starting empty`),{};let a=P1(t),o;try{o=Object.entries(i).map(([e,t])=>[e,_0(t,(t,n)=>{try{return H1(a,t)}catch(t){throw t instanceof V1?new V1(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof V1))throw e;return n(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let s=new Set,c=Object.fromEntries(o.map(([e,t])=>[e,g0(t,s)]));return s.size>0&&n(`warn`,`settings-history load: dropped the changes to ${[...s].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),c},save:r=>{let i=P1(t),a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,_0(t,e=>B1(i,e))]));try{h.mkdirSync(s.dirname(e),{recursive:!0}),dr(e,JSON.stringify(a),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw n(`error`,t),Error(t)}}}}const y0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function b0(e){return{...Object.fromEntries(y0.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 x0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function S0(e){let t=e=>({kind:`failed`,reason:e});if(!x0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!x0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!SF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${SF.join(` or `)}`)}return{kind:`ok`,value:e}}function C0(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const w0=e=>cU(e,`doctor-marks.json`,{},S0),T0=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],D0=e=>cU(e,`doctor-clicked-terminals.json`,[],T0);var O0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const k0=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),j0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=A0(e,t);return r===void 0?n:r.projectDir},M0=(e,t)=>A0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function N0(e){let t=new Map;for(let n of e.split(`
|
|
210
|
+
`)){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*P0(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 F0={pullRequests:e=>Object.keys(sq).some(t=>e.has(`git.${t}`)),rateLimits:e=>I0(e,`block`)||I0(e,`weekly`)};function I0(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function L0(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 R0(e,t,n){let r=CG(e),i=new Map(IC(e)),a=[...L0(e,t),...n].flatMap(e=>r.ofTemplate(e).flatMap(({reaches:e})=>e)),o=new Set,s=new Set;for(;a.length>0;){let e=a.pop();if(o.has(e))continue;o.add(e);let t=i.get(e),n=xG(e,t);n!==void 0&&s.add(n);for(let{reaches:e}of r.ofVariable(t))a.push(...e)}return s}function z0(e,t){let n=new Map;for(let r of Zv(Fx(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=>cy(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,R0(e,t,n.get(t))])),a=e=>r.filter(t=>F0[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const B0=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function V0(e){if(typeof e==`string`)return B0.exec(e)?.[1]}function H0(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 U0(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 W0(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=H0(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`?V0(U0(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 G0(e,t){return e===void 0?[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>y(e)):[e]}async function K0(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await q0(go(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function q0(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function J0(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await go(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await So(t,void 0,void 0);if(s.kind!==`ok`){Pe(`Failed to check agent file ${t}`);continue}i=n2(i,t,s.value);let c=$0(Co(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){Pe(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function Y0(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(Z0(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=U0(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||X0.test(r)?`claude-code`:`prompt`}const X0=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function Z0(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function Q0(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=Y0(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:W0(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 $0(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 e2(e){let t=$0(e);if(t.kind===`unparsed`)return Pe(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return Q0(t.value)}catch(e){return Pe(`Failed to project JSONL line: ${e}`),null}}function t2(e){let t=[];for(let n of e.split(`
|
|
211
211
|
`)){let e=e2(n);e&&t.push(e)}return t}function n2(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function r2(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function i2(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await So(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=n2(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,Co(c,e=>t2(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}
|
|
212
212
|
/*!
|
|
213
213
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -482,51 +482,51 @@ function run(argv) {
|
|
|
482
482
|
: iterm(argv[1], points),
|
|
483
483
|
);
|
|
484
484
|
}
|
|
485
|
-
`;async function k2(e,t){let n=await e.launch({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,O2,...t],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new O0(`the font`);return{kind:`failed`,reason:`osascript failed (${vt(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 A2=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),j2=e=>[...e].map(D2).join(`,`);async function M2(e,t,n){let r=await k2(e,[`font`,t.kind,t.name,j2(n)]);if(r.kind===`failed`)return r;let{lacks:i}=r.value;return{kind:`ok`,value:{font:t.name,lacks:i===null?null:A2(i)}}}function N2(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=>!
|
|
485
|
+
`;async function k2(e,t){let n=await e.launch({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,O2,...t],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new O0(`the font`);return{kind:`failed`,reason:`osascript failed (${vt(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 A2=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),j2=e=>[...e].map(D2).join(`,`);async function M2(e,t,n){let r=await k2(e,[`font`,t.kind,t.name,j2(n)]);if(r.kind===`failed`)return r;let{lacks:i}=r.value;return{kind:`ok`,value:{font:t.name,lacks:i===null?null:A2(i)}}}function N2(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=>!Tne(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const P2=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function F2(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=>N2(e,n));if(t!==null)return r[0];let i=r.find(e=>!P2(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 I2(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 k2(e,[`iterm`,i??``,j2(r)]);return a.kind===`failed`?a:F2(a.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:A2(e.lacks)})),i,t)}function L2(e,t){let n=e.split(`
|
|
486
486
|
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const R2=e=>e.replace(/[\\:,=-]/g,`\\$&`);async function z2(e,t,n){let r=await e.launch({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
487
|
-
`,`:family=${R2(t)}`],timeoutMs:3e3,category:`doctor.font`});if(!r.ok){if(r.reason===`rate-limited`)throw new O0(`the font`);return{kind:`failed`,reason:`fc-match failed (${vt(r)})`}}return L2(r.stdout,n)}function B2(e,t,n){return process.platform===`darwin`?M2(e,t,n):z2(e,t.name,n)}function V2(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function H2(e){return e===`darwin`?`Menlo`:`monospace`}const U2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function W2(e){let t=U2(e.font)?e.font:{},n=U2(t.normal)?t.normal:{},r=(U2(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 G2(e,t,n){let r;try{r=h.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=E2(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=W2(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!h.existsSync(i))continue;let a=G2(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}async function K2(e,t,n,r){let i=V2(r,t.XDG_CONFIG_HOME).find(e=>h.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:G2(i,r,0);if(a.kind===`failed`)return a;let o=a.value?.family??H2(process.platform),s=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),c=await B2(e,{kind:`family`,name:o},n);if(c.kind===`failed`)return c;let{font:l,lacks:u}=c.value;return{kind:`ok`,value:{font:l,from:l===o?s:`${s}; ${o} as fontconfig matches it`,lacks:u}}}const q2={iterm2:I2,alacritty:(e,t,n,r,i)=>K2(e,n,r,i)};function J2(e,t,n,r,i){return q2[t.name](e,t.version,n,r,i)}function Y2(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 X2=e=>
|
|
487
|
+
`,`:family=${R2(t)}`],timeoutMs:3e3,category:`doctor.font`});if(!r.ok){if(r.reason===`rate-limited`)throw new O0(`the font`);return{kind:`failed`,reason:`fc-match failed (${vt(r)})`}}return L2(r.stdout,n)}function B2(e,t,n){return process.platform===`darwin`?M2(e,t,n):z2(e,t.name,n)}function V2(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function H2(e){return e===`darwin`?`Menlo`:`monospace`}const U2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function W2(e){let t=U2(e.font)?e.font:{},n=U2(t.normal)?t.normal:{},r=(U2(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 G2(e,t,n){let r;try{r=h.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=E2(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=W2(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!h.existsSync(i))continue;let a=G2(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}async function K2(e,t,n,r){let i=V2(r,t.XDG_CONFIG_HOME).find(e=>h.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:G2(i,r,0);if(a.kind===`failed`)return a;let o=a.value?.family??H2(process.platform),s=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),c=await B2(e,{kind:`family`,name:o},n);if(c.kind===`failed`)return c;let{font:l,lacks:u}=c.value;return{kind:`ok`,value:{font:l,from:l===o?s:`${s}; ${o} as fontconfig matches it`,lacks:u}}}const q2={iterm2:I2,alacritty:(e,t,n,r,i)=>K2(e,n,r,i)};function J2(e,t,n,r,i){return q2[t.name](e,t.version,n,r,i)}function Y2(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 X2=e=>cU(e,`doctor-post-mortems-read.json`,{through:null},Y2);function Z2(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const Q2={realpath:e=>Z2(()=>h.realpathSync(e)),checkoutOf:Tn,digest:e=>Z2(()=>Sn(e)),nativeShipped:$o(process.platform,process.arch)};function $2(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const e4=e=>({marks:w0(e),clicked:D0(e),postMortemsRead:X2(e)}),t4=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function n4(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 r4(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 i4=/^(sshd|mosh-server)\b/;function a4(e,t){let n=N0(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of P0(n,t))if(i4.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}async function o4(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 O0(`the processes`);return{kind:`failed`,reason:`ps failed (${vt(n)})`}}return a4(n.stdout,t)}const s4=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function c4(e,t){let n=[];for(let r of e.split(`
|
|
488
488
|
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function l4(e){let t;try{t=h.realpathSync(e)}catch{return!1}let n=s4.exec(t)?.[1];return n!==void 0&&h.existsSync(s.join(n,`bin`,`cc-candybar`))}async function u4(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:c4(t.stdout,l4)}:{kind:`failed`,reason:`ps failed (${vt(t)})`}}async function d4(e,t){let n=await Ws(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 O0(`tmux`);return n.kind===`failed`?{kind:`failed`,reason:n.reason}:r4(n.stdout)}function f4(e,t,n){return{probeTmux:t=>d4(e,t),remoteLogin:t=>o4(e,t),fontInUse:(t,r,i)=>J2(e,t,r,i,n.home),loadConfig:t,home:n.home,managedSettingsDir:n.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??Ro(process.platform),install:Q2,daemons:()=>u4(e),forge:t=>_4(e,t),transcript:m4}}function p4(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
489
489
|
`)+1,i=n.lastIndexOf(`
|
|
490
490
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
491
|
-
`)){let t=$0(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function m4(e){let t=Do(e,
|
|
492
|
-
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const b4=e=>Z2(()=>Bo(e));function x4(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:jo(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:b4(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 S4(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function C4(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:
|
|
493
|
-
`:null,r=R4(e.value);return r===null?{stdout:n??Y4(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function L4(e){return Vr(e,()=>({kind:`stats`}),P4,e=>`stats`in e?e.stats:void 0)}function R4(e,t=H4){let n=N4.referenceSnapshot(),r=U4(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=B4(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function z4(e){return e.version===`1.208.
|
|
491
|
+
`)){let t=$0(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function m4(e){let t=Do(e,CF+1);return t.kind===`ok`?F(p4(t.value.buf,t.value.fromStart)):t}function h4(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 g4={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function _4(e,t){if(nc(t)===void 0)return{kind:`ok`,value:null};let n=cW(await e.launch({bin:`git`,args:[...sW],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=pW(n.value);if(r===null)return{kind:`ok`,value:null};let i=oW(r);if(i===null)return{kind:`ok`,value:null};let a=tW[i],o=g4[i],s=o.loginHost(aW(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return v4(a,s,o.nonZero,c)}function v4(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):nW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:QU(r.stderr)}):{kind:`failed`,reason:ZU(e,r)}}function y4(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
492
|
+
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const b4=e=>Z2(()=>Bo(e));function x4(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:jo(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:b4(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 S4(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function C4(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:One(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:Dne(t),tmuxClient:t}}}}async function w4(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(Sne(s))return{kind:`bundling`,name:s,version:c};if(!Cne(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 T4(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 E4(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function D4(e,t,n,r){return{pullRequests:await E4(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await E4(t.rateLimits,()=>r)}}function O4(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 k4(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=qq(d.config,r,()=>!1),p=await S4(e,t.tmux),m=C4(p,t.terminalEnv),h=[...new Set([...pne(f),...aF(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:w4(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),D4(e,z0(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:y4(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:h4(e,o),claudeSettings:x4({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:jo(Ao(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function A4(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;dr(e,qa(Po(e),t.path,JSON.stringify(t.value),Na));let r=e=>({...e,sources:b4(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||yi(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 j4={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},M4=16384;var N4=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<M4){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%M4}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:j4,file:j4,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},journalTurns:{gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0,queued: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},linkIds:{minted:0,reused:0,evicted:0,reservations:0,faults: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:wn,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,linkIds:e.linkIds,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 P4={connectMs:200,budgetMs:500};async function F4(e,t){return I4(await L4(e),t.includes(`--json`))}function I4(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${Jr(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
493
|
+
`:null,r=R4(e.value);return r===null?{stdout:n??Y4(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function L4(e){return Vr(e,()=>({kind:`stats`}),P4,e=>`stats`in e?e.stats:void 0)}function R4(e,t=H4){let n=N4.referenceSnapshot(),r=U4(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=B4(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function z4(e){return e.version===`1.208.2`&&V4(e)===En()?null:B4(e)}function B4(e){return{theirs:G4(e.version,V4(e)),mine:G4(wn,En())}}const V4=e=>e.sourceDigest??null,H4=Object.keys(N4.referenceSnapshot());function U4(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!W4(e))return[];if(!W4(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(...U4(e[i],t[i],a)):r.push(a)}return r}function W4(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function G4(e,t){return`${e} [${t===null?`no digest`:Cn(t)}]`}function K4(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function q4(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function J4(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 Y4(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${G4(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${J4(e.uptimeSec)}`),t.push(` rss ${K4(e.rssBytes)}`),t.push(` heapUsed ${K4(e.heapUsedBytes)}`),t.push(` heapTotal ${K4(e.heapTotalBytes)}`),t.push(` external ${K4(e.externalBytes)}`),t.push(` arrayBuffers ${K4(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 ${q4(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 ${q4(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 ${Mc(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 ${K4(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${K4(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 ${K4(e.renderCache.accountedBytes)} / ${K4(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(``),t.push(`journalTurns`),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(`
|
|
494
494
|
`)+`
|
|
495
|
-
`}const X4=e=>({kind:`ok`,value:e}),Z4=e=>({kind:`failed`,reason:e});var Q4=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const $4=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function e3(e){return $4.test(e)?e:null}function t3(e,t){let n=e.opener(t);if(n.kind===`failed`)return n;if(n.value===null)return X4(null);let r=n.value;return X4({app:r,forwarder:e.exists(ls(r))})}async function n3(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 r3(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}; the URL handler delivers a link naming ${e.name} 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=
|
|
496
|
-
`).join(` — `));let n=R4(t.value,[`handlerProbes`]);if(n!==null)return Z4(n);let r=[];for(let e of t.value.handlerProbes){let t=s3(e);if(t===null)return Z4(`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 X4({arrivals:r,otherBuild:z4(t.value)})}function s3(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 c3(e,t){let{home:n,clock:r}=t;return{platform:process.platform,name:n.name,sockets:{own:Vn(n),handler:Hn(n.name)},monotonic:()=>r.monotonic(),nonce:de,daemon:()=>o3(t),open:t=>{let n=i3(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>rt(r,100),opener:t=>{let n=i3(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,a3(t)]);if(n.kind===`failed`)return n;let r=n.value.trim();return X4(r===``?null:r)},exists:h.existsSync}}function l3(e){return Xs(()=>decodeURIComponent(e))}const u3=5e3;function d3(e,t,n){if(e.reason===`rate-limited`){n(`warn`,vt(e));return}throw e.reason===`aborted`?new qs(t):Error(`${t} failed (${vt(e)})`)}async function f3(e,t,n,r,i,a){let o=S(s.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:s.join(o,`stderr`),status:s.join(o,`status`)},c=e.launchJobSync(t,a);if(!c.ok){d3({...c,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}c.release();let l=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(c.pid),s=Yt(a.status);if(s!==null){if(s.kind===`exit`&&s.code===0)return;d3(s.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:w(a.stderr,`utf8`),exitCode:s.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()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await rt(e.clock,50)}}finally{E(o,{recursive:!0,force:!0,maxRetries:3})}}function p3(e,t){m3(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function m3(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const h3=(e,[t=``],n)=>{p3(t,n)},g3=new Set([`request`,`feed`]);function _3(e){if(!g3.has(e))throw new R(`unknown renderer ${JSON.stringify(e)}`);return e}const v3=(e,t,n)=>{let[r=``,i=``]=t,a=n.diagnosticCopy(e,_3(r),i);if(a===void 0)throw new R(`that message is no longer listed in session ${e}'s diagnostics — open ⚠ again and copy from there`);p3(a,n)},y3=(e,[t=``],n)=>{m3(n,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t],category:`click.open`},`open -a "Visual Studio Code"`)},b3=(e,t,n)=>{n.navigating.get(e,`toolbar-expanded`)?n.navigating.clear(e,`toolbar-expanded`):n.navigating.set(e,`toolbar-expanded`,`1`)},x3=(e,t,n)=>{let r=n.gates.state.gateFor(N3(n,e));if(t.length===0)throw new R(`set-state: <key>/<value> is required (have keys: ${r.listKeys().join(`, `)})`);if(t.length%2!=0)throw new R(`set-state: expected even-count <key>/<value> pairs, got ${t.length} segment(s) after session id (have keys: ${r.listKeys().join(`, `)})`);let i=[];for(let e=0;e<t.length;e+=2){let n=t[e],a=t[e+1];if(!n)throw new R(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let o=r.validate(n,a);if(!o.ok)throw new R(`set-state: pair ${e/2+1}: ${o.reason}`);i.push({key:n,value:o.value})}T3(n,e,`set-state`,i),n.navigating.setBatch(e,i);let a=i.map(e=>`${e.key}=${e.value}`).join(` `);n.log(`info`,`set-state: ${a} (session=${e})`)},S3=/^-?\d+$/;function C3(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const w3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!S3.test(i))throw new R(`step-state: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=N3(n,e),s=n.gates.state.gateFor(o),c=s.rangeParamsFor(r);if(!c)throw new R(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${s.listKeys().join(`, `)})`);let l=n.sessionState.get(e,r),u=l&&S3.test(l)?E3(c,parseInt(l,10)):D3(`step-state`,r,c,y$(o,t=>n.sessionState.get(e,t),r)),d=C3(u,a,c.min,c.max),f=s.validate(r,String(d));if(!f.ok)throw new R(`step-state: ${f.reason}`);T3(n,e,`step-state`,[{key:r,value:f.value}]),n.navigating.set(e,r,f.value),n.log(`info`,`step-state: ${r} ${u}→${f.value} (by ${a}, session=${e})`)};function T3(e,t,n,r){let i=r.filter(e=>e.key.startsWith(uP));if(i.length===0)return;let a=c$(N3(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new R(`${n}: refused — ${a.join(`; `)}`)}function E3(e,t){return Math.max(e.min,Math.min(e.max,t))}function D3(e,t,n,r){if(r===null)return n.min;if(!S3.test(r))throw new R(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return E3(n,parseInt(r,10))}function O3(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function k3(e,t){let n;try{n=JSON.parse(e)}catch{throw new R(`render origin is not JSON: ${e}`)}if(typeof n!=`object`||!n)throw new R(`render origin is not an object: ${e}`);let{projectDir:r,cwd:i,configFile:a,source:o}=n;if(typeof r!=`string`||typeof i!=`string`||a===void 0)throw new R(`render origin has the wrong shape: ${e}`);let s;try{s=a===null?null:H1(t,a)}catch(e){throw e instanceof V1?new R(`render origin: ${e.message}`):e}return{projectDir:r,cwd:i,target:O3(o,s)}}function A3(e,t){let n=j3(e,t);if(n===null)throw new R(`session ${t} has not rendered yet — no config to act on`);return n}function j3(e,t){let n=e.sessionState.get(t,KQ);return n===null?null:k3(n,e.storedRoot)}function M3(e,t,n){let r=j3(e,t);if(r===null)return;let{path:i}=I3(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function N3(e,t){return e.configFor(A3(e,t))}function P3(e,t){let n=j3(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function F3(e,t){let n=j3(e,t);return n===null?x$:T$(e.configFor(n))}function I3(e,t){return cU(e.locations,HU(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 R3=(e,t,n)=>{let[r=``,i=``]=t,a=A3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`set-config: <key>/<value> is required (have keys: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`set-config: ${c.reason}`);let l=I3(n,a),u=o$(o,t=>n.sessionState.get(e,t),r);_1(L3(n,e),l,[[u.key,c.value]]),n.reloadConfig(a),n.log(`info`,`set-config: ${u.key}=${c.value} → ${l.path} (session=${e})`)},z3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!S3.test(i))throw new R(`step-config: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=A3(n,e),s=n.configFor(o),c=n.gates.config.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new R(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${c.listKeys().join(`, `)})`);let u=I3(n,o),d=o$(s,t=>n.sessionState.get(e,t),r),f=g1(u.path,d.key),p=typeof f==`number`?E3(l,f):D3(`step-config`,r,l,b$(d.globals,r)),m=C3(p,a,l.min,l.max),h=c.validate(r,String(m));if(!h.ok)throw new R(`step-config: ${h.reason}`);_1(L3(n,e),u,[[d.key,h.value]]),n.reloadConfig(o),n.log(`info`,`step-config: ${d.key} ${p}→${h.value} (by ${a}) → ${u.path} (session=${e})`)},B3=(e,t,n)=>{let r=A3(n,e),i=n.configFor(r),a=t=>n.sessionState.get(e,t),o=i$(i,a),s=s$(i,a);if(o.length+s.length===0){n.log(`info`,`save: nothing unsaved (session=${e})`);return}let c=n.gates.state.gateFor(i),l=o.map(e=>{let t=c.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save: ${t.reason}`);return[e.target,t.value]});H3(`save`,c,s);let u=I3(n,r);v1(L3(n,e),u,l,s),n.reloadConfig(r);for(let t of[...o.map(e=>e.sessionKey),...s.map(e=>e.key)])n.sessionState.clear(e,t);n.log(`info`,`save: ${[...l.map(([e,t])=>`${e}=${t}`),...s.map(V3)].join(` `)} → ${u.path} (session=${e})`)},V3=e=>`${e.preset}/${e.id}.settings.${e.setting}=${yy(e.value)}`;function H3(e,t,n){for(let r of n){let n=t.validate(r.key,yy(r.value));if(!n.ok)throw new R(`${e}: ${n.reason}`)}}const U3=(e,t,n)=>{let r=A3(n,e),i=n.configFor(r),a=d$(i,t=>n.sessionState.get(e,t)),o=n.gates.state.gateFor(i),s=a.picks.map(e=>{let t=o.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save-preset: ${t.reason}`);return[e.configKey,t.value]});H3(`save-preset`,o,a.placements);let c=I3(n,r),l=T1(L3(n,e),c,a.from,a.globals,s,a.placements);n.reloadConfig(r);for(let t of[...sx.map(e=>e.sessionKey),...a.placements.map(e=>e.key)])n.sessionState.clear(e,t);n.sessionState.set(e,ax.preset.sessionKey,l),n.log(`info`,`save-preset: ${[`${l} from=${a.from}`,...s.map(([e,t])=>`${e}=${t}`),...a.placements.map(V3)].join(` `)} → ${c.path} (session=${e})`)},W3=(e,t,n)=>{let r=A3(n,e),i=p$(n.configFor(r),t=>n.sessionState.get(e,t));if(i.kind===`rule`)throw new R(`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 a=I3(n,r);E1(L3(n,e),a,i.theme,i.look),n.reloadConfig(r);let o=new Set(i$(n.configFor(r),t=>n.sessionState.get(e,t)).map(e=>e.sessionKey)),s=ex.map(e=>ax[e].sessionKey).filter(e=>!o.has(e));for(let t of s)n.sessionState.clear(e,t);n.log(`info`,`save-theme-default: ${i.theme} ${ex.map(e=>`${e}=${i.look[e]}`).join(` `)} → ${a.path} (session=${e})`)},G3=(e,t,n)=>{let[r=``]=t;if(!r)throw new R(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let i=A3(n,e),a=I3(n,i);D1(L3(n,e),a,r),n.reloadConfig(i);let o=ax.preset.sessionKey;n.sessionState.get(e,o)===r&&n.sessionState.clear(e,o),n.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${e})`)},K3=(e,t,n)=>{let r=t,i=A3(n,e),a=n.gates.config.gateFor(n.configFor(i)).listKeys(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new R(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=I3(n,i),c=r.map(m$),l=c.flatMap(e=>e.fileKeys),u=c.flatMap(e=>e.sessionKeys);S1(L3(n,e),s,l),n.reloadConfig(i);for(let t of u)n.sessionState.clear(e,t);n.log(`info`,`reset-config: ${[...l,...u.map(e=>`session:${e}`)].join(` `)} ← ${s.path} (session=${e})`)};function q3(e,t){let n=(e,t)=>[...$v(Rx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Fx(t.presets).flatMap(e=>n(t,e).map(t=>dP(UM(e),Yv(t)))));return Fx(e.presets).flatMap(t=>n(e,t).map(e=>({member:dP(UM(t),Yv(e)),node:e})).filter(({member:e})=>!r.has(e)))}function J3(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[sP]:[]])}const Y3=(e,t,n)=>{let[r=``,i=``]=t,a=A3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`apply-layout-op: <key>/<op> is required (have: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`apply-layout-op: ${c.reason}`);let l=rz(c.value);if(l===null)throw new R(`apply-layout-op: "${c.value}" is not a layout op token`);let u=I3(n,a),d=O1(L3(n,e),u,r,l);n.reloadConfig(a);let f=J3(q3(o,n.configFor(a)),n.sessionState.get(e,sP)).filter(t=>n.sessionState.get(e,t)!==null);for(let t of f)n.sessionState.clear(e,t);n.log(`info`,`apply-layout-op: ${r} ${c.value} → ${u.path} placed=${JSON.stringify(d)} released=${JSON.stringify(f)} (session=${e})`)},X3=(e,t,n)=>{n.journal.commit();let r=n.history.undo(e);n.journal.wrote(),M3(n,e,r),n.log(`info`,`undo: restored ${u0(r)} (session=${e})`)},Z3=(e,t,n)=>{let{step:r,discarded:i}=n.navigation.back(e,n.sessionState,n.gates.state.gateFor(N3(n,e))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);n.log(`info`,`back: ${a} discarded=${i} (session=${e})`)},Q3=(e,t,n)=>{n.journal.commit(),n.journal.wrote();let r=n.history.rewind(e);M3(n,e,r),n.log(`info`,`rewind: put back ${u0(r)||`nothing`} as edit mode found it (session=${e})`)},$3=(e,t,n)=>{n.journal.commit();let r=n.history.redo(e);n.journal.wrote(),M3(n,e,r),n.log(`info`,`redo: re-applied ${u0(r)} (session=${e})`)},e6=(e,t,n)=>{n.effect({kind:`apply-update`})};function t6(e,t){let n=e.sessionState.get(t,qQ);if(n===null)throw new R(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new R(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new R(`client hints record is not an object: ${n}`);return yr(r)}function n6(e,t,n){let r=QF(n);e.sessionState.setBatch(t,hI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${nI(n.config)} ${pI(n.nerdFont,n.marks)} ${rI(n.terminal,n.clicked)} ${iI(n.terminal,n.width)} ${aI(n.install)} ${sI(n.daemon)} ${cI(n.data)} ${fI(n.transcripts)} ${lI(n.frames,n.claudeSettings)} ${dI(n.claudeSettings.origin.sources)} (session=${t})`)}function r6(e,t,n){e.effect({kind:`doctor`,session:t,step:n,arrival:e.arrival})}function i6(e,t){let n=e=>{throw Error(`doctor: the gather ${e}; a gather writes nothing`)};return{get:(n,r)=>{let i=e.get(n,r);return t.set(JSON.stringify([n,r]),{what:r,value:i,again:e=>e.get(n,r)}),i},values:()=>n(`read every key; a gather reads keys by name`),revision:t=>e.revision(t),set:(e,t)=>n(`set ${t}`),setBatch:()=>n(`wrote a batch`),clear:(e,t)=>n(`cleared ${t}`)}}function a6(e,t,n){for(let{what:t,value:r,again:i}of n.reads)if(i(e.sessionState)!==r)return t;let r=e.doctor.loadConfig(A3(e,t));return r.config===n.load.config&&r.error===n.load.error&&r.warning===n.load.warning?null:`config`}function o6(e,t){let{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}=t6({sessionState:e},t);return{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}}async function s6(e,t,n,r){let i=new Map,a={...e,sessionState:i6(e.sessionState,i)},o=e=>JSON.stringify(o6(e,t)),s=o6(e.sessionState,t);i.set(`hints`,{what:qQ,value:JSON.stringify(s),again:o});let c=r.loadConfig(A3(a,t)),l={kind:`clicked`,sessionId:t,via:n.via},u=e.clients.ofSession(t,e.now()),d;try{d=await k4({...r,loadConfig:()=>c},s,A3(a,t),e=>a.sessionState.get(t,e),{kind:`ok`,value:e.serving()},{kind:`ok`,value:u.map(e=>e.rateLimits)},{kind:`ok`,value:u.map(e=>e.transcript)},l,{kind:`ok`,value:M0(l,u)},O4(t,u),t4(e.doctorStores))}catch(e){throw e instanceof O0?new R(e.message):e}return{facts:d,install:$2(r.install,e.bundle,u.map(e=>e.client)),stamp:{load:c,reads:[...i.values()]}}}async function c6(e,t){let n=n4(e.doctor),r=t.session;return e.journalTurns.gathering(async()=>{let i=await s6(e,r,t.arrival,n);return a6(e,r,i.stamp)===null?i:s6(e,r,t.arrival,n)})}function l6(e,t,n,{facts:r,install:i}){let a=t4(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:T4(n),install:i,clicked:u6(e,n,o)}}function u6(e,t,{terminal:n,clicked:r}){let i=n.kind===`seen`?xF(n.identified):null;if(i===null||t.via!==`link`)return r;try{return e.doctorStores.clicked.update(e=>E0(e,i))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(i)}: ${t instanceof Error?t.message:String(t)}`),r}}const d6={run:(e,t,n,r)=>n6(e,t,r),fix:(e,t,{check:n},r)=>{let i=n.probe(r);if(i.ok||i.fix===void 0)throw new R(`doctor-fix: ${n.label} — ${i.ok?`nothing to fix`:i.reason}`);let a=A4(e.doctorStores,i.fix,r);if(a.kind===`failed`)throw new R(`doctor-fix: ${n.label} — ${a.reason}`);e.log(`info`,`doctor-fix: ${n.name} → ${jne(i.fix)} (session=${t})`),n6(e,t,a.value)},mark:(e,t,{check:n,mark:r},i)=>{let a=n.probe(i);if(a.ok||a.sighting===void 0)throw new R(`doctor-mark: ${n.label} — ${a.ok?`nothing to mark`:`shows nothing to look at`}`);let o=e.doctorStores.marks.update(e=>C0(e,n.name,a.sighting.id,r));if(o.kind===`failed`)throw new R(`doctor-mark: ${o.reason}`);e.log(`info`,`doctor-mark: ${n.name} ${r} on ${a.sighting.id} (session=${t})`),n6(e,t,{...i,marks:o})}};function f6(e,t,n){let r=t.session,i=a6(e,r,n.stamp);if(i!==null)throw new R(`doctor: the session's ${i} changed during the doctor's probes — click again`);p6(e,r,t.step,l6(e,r,t.arrival,n))}function p6(e,t,n,r){let i=d6[n.kind];i(e,t,n,r)}const m6=(e,t,n)=>{r6(n,e,{kind:`run`})},h6=(e,t)=>{let n=e3(l3(e));if(n===null)throw new R(`probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new R(`probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`probe: arrived nonce=${n} delivery=${r.kind}`)},g6=(e,t,n)=>{let[r=``]=t,i=$F(r);if(i===void 0)throw new R(`doctor-fix: unknown check "${r}"`);r6(n,e,{kind:`fix`,check:i})},_6=(e,t,n)=>{let[r=``,i=``]=t,a=$F(r);if(a===void 0)throw new R(`doctor-mark: unknown check "${r}"`);if(!TF.includes(i))throw new R(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${TF.join(` or `)}`);r6(n,e,{kind:`mark`,check:a,mark:i})},v6=(e,t,n)=>{let[r=``]=t,i=Object.values(n.configFor(A3(n,e)).actions).filter(e=>`slash`in e),a=i.find(e=>e.slash===r);if(a===void 0)throw new R(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(i.map(e=>e.slash))].join(`, `)||`none`})`);let o=LQ(t6(n,e).tmux);if(o.kind===`refused`)throw new R(`${r} was not typed: ${o.reason}`);n.effect({kind:`type-slash`,pane:o.hint,line:a.slash})};function y6(e,[t=``,n=``,r=``],i){let a=A3(i,e),o=i.configFor(a).actions,s=Object.hasOwn(o,t)?o[t]:void 0;if(s===void 0||!(`run`in s))throw new R(`"${t}" is not a run action this session's config declares`);let c=Jx(s);if(!i.links.signer.verify({sessionId:e,action:t,declaration:c,evaluated:n},r))throw new R(`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 l;try{l=JSON.parse(n)}catch{throw new R(`run ${t}: what the link carries is not JSON`)}let[u,...d]=l.run;if(u===void 0||u===``)throw new R(`run ${t}: the program evaluated to nothing`);let f=i.sourcesFor(a);return{sessionId:e,action:t,argv:[u,...d],envOverlay:{...b0({sessionId:e,projectDir:a.projectDir,claudeConfigDir:t6(i,e).claudeConfigDir}),...l.env},cwd:s.cwd??i.locations.homeDir,refreshes:s.refreshes.map(e=>({name:e,storage:f.get(e)}))}}const b6=new Map([[fS,h3,[1,1]],[pS,y3,[1,1]],[uS,x3,[0,1/0]],[dS,w3,[2,2]],[hS,R3,[2,2]],[gS,z3,[2,2]],[xS,K3,[0,1/0]],[_S,B3,[0,0]],[vS,U3,[0,0]],[yS,W3,[0,0]],[bS,G3,[1,1]],[SS,Y3,[2,2]],[CS,X3,[0,0]],[wS,$3,[0,0]],[TS,Z3,[0,0]],[ES,Q3,[0,0]],[mS,b3,[0,0]],[DS,e6,[0,0]],[OS,m6,[0,0]],[kS,g6,[1,1]],[AS,_6,[2,2]],[MS,v6,[1,1]],[`run`,(e,t,n)=>{let r=y6(e,t,n);n.effect({kind:`run`,id:n.runs.superseded(r),run:r})},[3,3]],[NS,(e,t,n)=>{let[r=``,i=``,a=``]=t,o=i;if(!n.links.signer.verify(WU(e,r,o),a))throw new R(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let s=UU(HU(n.stateDir),r,o);if(s.kind===`failed`)throw Error(`${r} was not ${o}: ${s.reason}`);n.journal.wrote();let{superseded:c,absent:l,unchecked:u}=s.value;n.log(`info`,`repo-config: ${r} ${o} superseded=${c.join(`,`)||`-`} absent=${l.join(`,`)||`-`} unchecked=${u.length===0?`-`:JSON.stringify(u)} (session=${e})`),n.reloadConfig(A3(n,e))},[3,3]],[PS,v3,[2,2]]].map(([e,t,n])=>[e,{handler:t,takes:n}]));new Set(b6.keys());function x6(e,t,n){let[r=``,...i]=n.split(`/`);return{verb:e,leaf:t,session:S6(r),args:Ys(()=>i.map(decodeURIComponent))}}function S6(e){let t=Ys(()=>decodeURIComponent(e));return t.ok?$Z(t.value):{ok:!1,problem:`has ${t.problem}`}}function C6({verb:e,value:t}){let n=b6.get(e);return n===void 0?{verb:e,leaf:n}:x6(e,n,t)}function w6(e){return XS(JS(e)).map(C6)}function T6(e){return e.find(e=>e.leaf!==void 0)?.session??null}function E6(e,t){return T6(e===`dispatch`?w6(t):[C6({verb:e,value:t})])}function D6({verb:e,leaf:t,session:n,args:r},i,a){let o=[];try{if(!n.ok)throw new R(`session id ${n.problem}`);if(!i?.ok)throw new R(`its click's own session is refused, so no step of it runs`);if(i.id!==n.id)throw new R(`names session ${n.id}, not the session its click is in`);if(!r.ok)throw new R(r.problem);let[e,s]=t.takes;if(r.value.length<e||r.value.length>s)throw new R(`reads ${e===s?e:`${e} to ${s}`} after its session, and the link carries ${r.value.length}`);t.handler(n.id,r.value,{...a,effect:e=>void o.push(e)})}catch(t){throw t instanceof R&&O6.get(e)?.(a,{sid:i?.ok?i.id:`-`,args:r.ok?r.value:[],reason:t.message}),t}for(let e of o)a.effect(e)}const O6=new Map([[`run`,(e,{sid:t,args:[n],reason:r})=>e.runs.refused(t,n||`-`,r)]]);function k6(e,t,n){let r=[],i=!1;for(let a of e){if(a.leaf===void 0){r.push(`unknown effect verb "${a.verb}"`);continue}try{D6(a,t,n)}catch(e){e instanceof R||(i=!0),r.push(`${a.verb}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){t?.ok&&kZ(n.sessionState,t.id,r.join(`
|
|
497
|
-
`),n.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new R(e)}}function A6(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}function j6(e,t,n){let r=e===null?null:P3(t,e),i=t.history.begin(),a=t.navigation.begin(i.sessionState),o=[],s=e=>O$(e,e=>F3(t,e),e=>t.log(`info`,e)),c=[];try{n({...t,sessionState:s(i.sessionState),journal:i,navigating:s(a.sessionState),effect:e=>void c.push(e)})}catch(e){o.push(e)}for(let e of[a,i])try{e.commit()}catch(e){o.push(e)}if(r!==null)try{let e=r.read();c.push(...t.lanes.clicked(r.sessionId,i.written()?r.before:e,e))}catch(e){o.push(e)}t.described(c),A6(o)}function M6(e,t,n){return(r,i)=>{if(i.gone())throw new Js(e);let a=t(r),o=T6(a),s=o?.ok?o.id:null;i.journalTurns.take(e,()=>j6(s,i,e=>{try{n(a,o,e)}finally{s!==null&&i.clickLanded(s)}}))}}const N6=new Map([...[...b6].map(([e,t])=>[e,M6(e,n=>[x6(e,t,n)],(e,t,n)=>{for(let r of e)D6(r,t,n)})]),[lS,M6(lS,w6,k6)],[jS,h6]]);Object.freeze([...N6.keys()]);function P6(e){let t=N6.get(e);return t===void 0?null:{name:e,run:t}}function F6(e,t,n){n.journalTurns.take(`menu-idle`,()=>j6(e,n,n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=D$(F3(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:ea}))),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 I6=[],L6={request:({req:e,facts:t},{verbCtx:n})=>{let r=n.journalTurns.take(`request`,()=>(H6(n.sessionState,e),{effects:n.lanes.arrived(e),revision:n.sessionState.revision(e.sessionId)}));return BZ(t,{revision:String(r.revision),effects:r.effects.map(e=>GQ(e)).join(`,`)||`-`}),{answer:void 0,effects:r.effects,facts:[]}},click:({verb:e,value:t,arrival:n,gone:r},{verbCtx:i})=>{let a=[],o=null;try{e.run(t,{...i,arrival:n,gone:r,described:e=>void a.push(...e)})}catch(e){o={error:e}}return{answer:o,effects:a,facts:[]}},"menu-idle":({session:e,idle:t},{verbCtx:n})=>{let r=[];return F6(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":({of:e,done:t},n)=>{let{verbCtx:r}=n;return{answer:r.journalTurns.take(`effect-done`,()=>{let i=B6(t,n);return i.kind===`failed`&&e.session!==null&&kZ(r.sessionState,e.session,i.said,r.now()),i}),effects:I6,facts:[]}},answered:({session:e,errors:t},{verbCtx:n})=>(n.journalTurns.take(`answered`,()=>AZ(n.sessionState,e,t)),{answer:void 0,effects:I6,facts:[]})},R6=({outcome:e})=>e,z6={launch:R6,"type-slash":R6,"apply-update":R6,run:R6,"lane-setup":R6,doctor:({effect:e,outcome:t},n)=>t.kind===`failed`?t:(f6(n,e,t.gathered),Gs)};function B6(e,t){let n=z6[e.effect.kind];try{return n(e,t.verbCtx)}catch(n){return V6(e.effect,n,t.log)}}function V6(e,t,n){return t instanceof R||t instanceof qs||n(`error`,`apply: ${GQ(e)} threw: ${k(t)}`),Ks(t instanceof Error?t.message:String(t))}function H6(e,t){let{client:n,configEnv:r,...i}=t.hints,a=[{key:qQ,value:JSON.stringify(i)},{key:KQ,value:t.originRecord}];e.setBatch(t.sessionId,a.filter(({key:n,value:r})=>e.get(t.sessionId,n)!==r))}async function U6(e,t){let n=L6[e.kind],r=n(e,t),i=$6(e),a=Y6[e.kind],o=a(e,r);return o!==null&&t.log(o.level,WZ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>GQ(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?W6:o8(t,i,r.effects)}}const W6=Promise.resolve();async function G6(e,t){return await U6(e,t),t.draw(e.req,e.at,e.waitEndsAt,e.facts)}const K6={level:`info`,facts:[[`outcome`,`ok`]]},q6=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),J6={ok:`info`,failed:`warn`},Y6={request:()=>null,click:(e,{answer:t})=>t===null?K6:q6(t),"menu-idle":()=>K6,answered:()=>K6,"effect-done":({done:e},{answer:t})=>({level:J6[t.kind],facts:[[`effect`,GQ(e.effect)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},X6={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({verb:e,session:t})=>({verb:e.name,session:t}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e,answered:({session:e})=>({verb:`answered`,session:e})};function Z6(e,t,n,r){e(r instanceof qs?`info`:`error`,`apply: ${t} not applied (${n}): ${k(r)}`)}function Q6(e,t,n){return U6(e,t).then(()=>void 0,r=>Z6(t.log,e.kind,n,r))}function $6(e){let t=X6[e.kind];return t(e)}const e8={launch:({spec:e,what:t},{verbCtx:n})=>t8(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await RQ(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:Ks(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),Gs),run:({id:e,run:t},{verbCtx:n})=>n.runs.run(e,t),"lane-setup":(e,{verbCtx:t})=>t.lanes.setup(e),doctor:async(e,{verbCtx:t})=>({kind:`gathered`,gathered:await c6(t,e)})};async function t8(e,t,n){let r=await e.launch({...t,timeoutMs:u3});return r.ok?Gs:Ks(`${n} failed (${vt(r)})`)}async function n8(e,t){let n=e8[e.kind],r;try{r=await n(e,t)}catch(n){r=V6(e,n,t.log)}return{effect:e,outcome:r}}const r8={launch:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"type-slash":{key:({pane:e})=>({kind:`pane`,tmux:e}),paneWhenReached:!1},"apply-update":{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},run:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"lane-setup":{key:({sessionId:e,lane:t})=>({kind:`lane`,session:e,lane:t}),paneWhenReached:!0},doctor:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1}};function i8(e,t){return r8[e.kind].key(e,t)}function a8(e,t,n,r){let i=e=>r8[e.kind].paneWhenReached,a=[...n.filter(e=>!i(e)),...n.filter(i)],o=W6;for(let n of a){let i=o;o=e.performing(i8(n,t),async()=>{await i,await r(n)})}return o}function o8(e,t,n){return a8(e.verbCtx.journalTurns,t,n,async n=>{let r=await n8(n,e);await Q6({kind:`effect-done`,of:t,done:r},e,`${GQ(n)} ${r.outcome.kind}${`said`in r.outcome?`: ${r.outcome.said}`:``}`)})}function s8({projectDir:e,cwd:t,target:n},r){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path===void 0?null:B1(r,n.path),source:n.source})}function c8(e,t,n){let{tokens:r}=ne({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:DP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function l8(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=_r.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${_r.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function u8(e,t,n,r,i){let{report:a}=YZ(e.hookData),o=[];for(let e of a.missingRequired)o.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of a.typeMismatches)o.push(`field '${e}' expected ${t}, got ${n}`);let s=$Z(e.hookData?.session_id);s.ok||o.push(`field 'session_id' ${s.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&o.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&o.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let c=l8(e.encoding);c.ok||o.push(c.problem);let l=Yr(e.deadline);if(l.kind===`refused`)return{ok:!1,problems:[...o,l.problem]};if(o.length>0||!s.ok||!c.ok)return{ok:!1,problems:o};for(let e of a.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let d=yr(e),{configFile:f,refusedArgs:p}=c8(e.args,e.cwd,r),m=P1(i),h=AP(f,d.configEnv),g={projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:h.source===`search`?h:{...h,path:U1(m,h.path)}};return{ok:!0,req:{...e,deadline:l,encoding:c.encoding,sessionId:s.id,hints:d,rateLimits:gne(e.hookData),requested:g,originRecord:s8(g,m),refusedArgs:p}}}function d8(e,t){switch(e){case`vars`:return{what:e,vars:f8(t)};case`segments`:return{what:e,segments:_8(t)};case`config`:return{what:e,config:x8(t)}}}function f8(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=h8(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=p8(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:m8(r.lastUpdatedMs(),t.clock)})}return o}function p8(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 m8(e,t){return e===null?null:Math.max(0,t.now()-e)}function h8(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,g8(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}`,g8(i));return t}function g8(e){return e.kind}function _8(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=y8(n),o=v8(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:b8(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function v8(e){let t=new Map;for(let n of Fx(e.presets))for(let r of $v(Rx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Yv(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function y8(e){let t=[],n=new Set;for(let r of $v(Tx(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 b8(e,t,n){let r=new Set([...CC(e,t).keys()].flatMap(e=>BC(e,n)));return Array.from(r).sort()}function x8(e){return e===null?null:e.config}const S8=[`vars`,`segments`,`config`];function C8(e){return typeof e==`string`&&S8.includes(e)}const w8=e=>({resp:e,exitAfterFlush:null,delivered:lQ}),T8=e=>({kind:`reply`,...e}),E8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},D8=(e,t)=>T8(w8({ok:!1,error:t,code:e,daemonV:3}));function O8(e){let t=$Z(e.sessionId);if(!t.ok)return D8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return D8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${gb.join(`, `)}): it predates the lane toggles — update it`);let n=wb(e.lane);return n===null?D8(`BAD_REQUEST`,`subscribe needs a lane, one of ${gb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}function k8(e){let{session:t,path:n,seconds:r}=e,i=$Z(t);if(!i.ok)return{ok:!1,problem:`record's session ${i.problem}`};if(typeof n!=`string`||!u(n))return{ok:!1,problem:`record's path is not an absolute path: ${JSON.stringify(n)}`};let a=Nr(r);return a.ok?{ok:!0,session:i.id,path:n,seconds:a.seconds}:{ok:!1,problem:`record's seconds ${JSON.stringify(r)} ${a.problem}`}}function A8(e,t){let n=k8(t);if(!n.ok)return D8(`BAD_REQUEST`,n.problem);let{session:r,path:i,seconds:a}=n;return{kind:`held`,start:t=>cQ(e.recorder,e.clock,r,i,a,t).then(e=>w8({ok:!0,recorded:e}),e=>w8({ok:!1,error:e instanceof Error?e.message:String(e),code:e instanceof sQ?`RENDER_FAILED`:`BAD_REQUEST`,daemonV:3}))}}function j8(e,t){return e.v===3?null:(e.v>3?t(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):t(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:lQ})}async function M8(e,t,n,r,i){if(t.kind===`url`)return T8(w8(await B8(e,t.frame,n,r,i)));let a=t.req;if(!a||typeof a!=`object`||typeof a.v!=`number`)return D8(`BAD_REQUEST`,`malformed request`);let o=j8(a,e.log);return o===null?a.kind===`subscribe`?O8(a):a.kind===`record`?A8(e,a):typeof a.kind!=`string`||!Object.hasOwn(E8,a.kind)?D8(`BAD_REQUEST`,`unknown kind`):T8(await N8(e,a,n,r,i)):o}async function N8(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,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:w}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:lQ};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return w8(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 w8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:P8(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:yo(),renderCache:c.stats,effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:e.sessionState.size(),observers:e.sessionState.observers(),revision:e.sessionState.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),linkIds:e.linkIds.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(st(new Date(o.now()))),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:t4(w)})});if(t.kind===`render`){let c=new Date(o.now()),l=st(c),u=o.monotonic(),d=et(r,u),f=[],p=++a.requestsTotal,m=u8(t,a,e.log,e.home,e.storedRoot),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Ao(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:_ne(t.hookData),frame:n},l,p);m.ok&&(BZ(f,{sid:m.req.sessionId}),h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await G6({kind:`request`,req:m.req,at:l,waitEndsAt:$e(u,Xr(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({resp:t,motion:n,answersClick:r,pipeShown:i,delivered:a})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r.length>0&&Q6({kind:`answered`,session:m.req.sessionId,errors:r},e,`sid=${m.req.sessionId}`),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:U8(e),resp:uQ(e),delivered:lQ})):X8(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,BZ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:_,line:v}=UZ(`render`,f,g.outcome,tt(o,u));return e.log(_,v),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return w8(await R8(e,r,n,i,(n,r)=>z8(e,t,n,r)));if(t.kind===`debug`){if(!C8(t.what))return w8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${S8.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`?L8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??nx(`colorCompatibility`)):I8};return w8({ok:!0,debug:d8(t.what,n)})}throw Error(`no reply for request ${k(t)}`)}function P8(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 F8={endcaps:nx(`endcaps`),colorCompatibility:nx(`colorCompatibility`),wrap:nx(`autoWrap`),padding:nx(`padding`),width:1/0},I8=new Map;function L8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,fne(i,{...F8,colorCompatibility:t}));return n}async function R8(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${et(t,o)}ms`]],c=await i(s,()=>n()||r());BZ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=UZ(`click`,s,c,tt(a,o));return e.log(l,u),J8(c)}async function z8(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};BZ(n,{via:`cli`});let{url:a}=t;return typeof a==`string`?V8(()=>K8(e,a,i,n,r)):{kind:`bad-request`,problems:[`a click's link is a string, got ${typeof a}`]}}async function B8(e,t,n,r,i){return R8(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(BZ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Ar.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${k(i)} is not one this daemon speaks (${[...Ar].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return V8(()=>K8(e,a,o,n,r))})}async function V8(e){try{return await e()}catch(e){return H8(e)}}function H8(e){return e instanceof R?{kind:`bad-request`,problems:[e.message]}:e instanceof Js?{kind:`abandoned`,error:e}:U8(e)}function U8(e){return e instanceof qs?{kind:`closing`,error:e}:{kind:`threw`,error:e}}const W8={link:`to`,"tmux-status":`linkTo`},G8={link:`verb`,"tmux-status":`linkVerb`};async function K8(e,t,n,r,i){let a=$S(t);if(!a.ok)return{kind:`bad-request`,problems:[a.problem]};BZ(r,{[W8[n.via]]:a.to});let o=e.links.to;return a.to===o?q8(e,a.verb,a.value,n,r,i):{kind:`bad-request`,problems:[`the link is addressed to renderer ${JSON.stringify(a.to)}, and this is ${JSON.stringify(o)}`]}}async function q8(e,t,n,r,i,a){if(t===`range`)return r.via===`tmux-status`?{kind:`bad-request`,problems:[`a status-line link names another status-line click`]}:(BZ(i,{verb:t}),Y8(e,n,i,a));let o=P6(t);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};BZ(i,{[G8[r.via]]:t});let s=E6(t,n),c=s?.ok?s.id:null;BZ(i,{sid:c??`-`});let{answer:l}=await U6({kind:`click`,verb:o,value:n,arrival:r,session:c,gone:a},e);if(l!==null)throw l.error;return{kind:`ok`}}function J8(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 uQ(e.error)}}async function Y8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);return s.kind===`refused`?o(s.reason):(BZ(r,{link:s.url}),$i(s.url)?K8(e,s.url,{via:`tmux-status`},r,i):(await f3(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,u3,e.tmp),{kind:`ok`}))}const X8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:lQ});function Z8(e,t){let n=ce(`sha256`).update(t).digest(`hex`).slice(0,16);return s.join(e,`update-act`,n)}const Q8={kind:`idle`};function $8(e){if(e===null)return Q8;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 e5=e=>({stdout:s.join(e,`stdout`),stderr:s.join(e,`stderr`),status:s.join(e,`status`)}),t5=e=>s.join(e,`record.json`);function n5(e){let t;try{t=h.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 r5(e){let t=Do(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 i5(e,t){let n=s.join(e,`.removed-${t}-${process.pid}`);try{h.renameSync(s.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}h.rmSync(n,{recursive:!0,force:!0})}const $ne=e=>e.now()-o.uptime()*1e3;async function ere(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 tre(e){try{return JSON.parse(h.readFileSync(t5(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const nre=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function rre(e,t,n,r){let i=null;async function a(a){let o=s.join(e,String(a)),c=tre(o);if(c===null)return null;if((i===null||!nre(i.record,c))&&(i={record:c,ours:await ere(c,t,n,$ne(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=e5(o),u=Yt(l.status),d=u===null?null:r5(l.stderr)??r5(l.stdout);if(!h.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=n5(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${s.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function ire(e,t,n){h.mkdirSync(e,{recursive:!0});let r=h.mkdtempSync(s.join(e,`.claim-`));try{return h.writeFileSync(t5(r),JSON.stringify(n)),h.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{h.rmSync(r,{recursive:!0,force:!0})}}async function are(e,t,n,r,i,a,o,c){let l=(n??0)+1,u=s.join(t,String(l)),d=e.launchJobSync(i,e5(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!ire(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return a5;if(n5(t).some(e=>e>l))return i5(t,l),a5;f=!0}finally{f?d.release():d.withdraw()}for(let e of n5(t).filter(e=>e<l))i5(t,e);return{ok:!0,act:l}}const a5={ok:!1,reason:`another act claimed this bundle first`};function ore(e,t,n){let r=e5(s.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}var o5=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 s5(e){return e.kind===`source`?e.newer.digest:Ko(e.newer)}const c5=e=>`${e.version} [${Cn(e.digest)}]`;function l5(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:c5(e.newer),running:c5(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Ko(e.newer),running:Ko(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Jo}@${Ko(e.newer)}`,`install`]}}}}function sre(e,t,n){if(e===null)return[];let r=s5(e);if(!n.enabled||n.dismissed===r)return[];let i=l5(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(`
|
|
498
|
-
`),c=t.kind===`running`?vU(`[${i.busy}]`,null):vU(`[${i.act}]`,GS(n.to,[{verb:DS,args:[n.sessionId]}])),l=[vU(a,null),c,vU(`[dismiss]`,GS(n.to,[{verb:uS,args:[n.sessionId,Pz,r]}])),vU(`[disable]`,GS(n.to,[{verb:hS,args:[n.sessionId,Fz,`false`]},{verb:uS,args:[n.sessionId,Iz,`false`]}]))],u=o.map(e=>[vU(e,null)]);return[{severity:hU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function cre(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return lre(t)}}function lre(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function ure(e){switch(e.kind){case`current`:return[`info`,`build: current ${c5(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${c5(e.source)}, running ${c5(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function dre(e){switch(e.kind){case`current`:return[`info`,`release: current ${Ko(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Ko(e.latest)}, running ${Ko(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Ko(e.installed)}, latest ${Ko(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function fre(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=so(`unread`),g=so(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new qs(`apply-update`);return t},v=rre(s,_,r,n),y=null,b=null,x=Fe(m),S=Fe(m),C=new o5,w=e=>C.run(`acts`,e),T=!1,E=[],ee=(e,t)=>{E.push(n.every(t,e,{unref:!0}))},D=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function te(){let e=D(),t=e===null?null:s5(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(Pz,[t])})}function O(){let e=T?I:cre(h,g),r=GZ(t.get(),e,ut(n));(0,X.runInAction)(()=>t.set(r)),te()}function k(){let e=On(a,()=>N(o));return h=F(e),x(ure(e)),O(),e}async function ne(){let e=Xo(wn,await Yo(Jo,d,u,n));g=F(e),S(dre(e)),O()}let A=null,re=Fe(m);async function ie(e){try{let t=await e();return A=null,{ok:!0,value:t}}catch(e){return e instanceof qs?{ok:!1,error:e.message}:(A=`update act files (${s}): ${e.message}`,re([`error`,A]),{ok:!1,error:A})}}function ae(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=ore(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 oe(){let e=await ie(async()=>{let e=await v.read();return T||ae(e),e});if(T||!e.ok)return;let t=$8(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`),k(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let se;async function ce(){await w(oe),!T&&(se=n.after(2e3,()=>void ce(),{unref:!0}))}return{arm(){let e=k();ee(k,c),E.push(()=>se?.()),ce(),e.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),l))},close(){T=!0,O(),E.forEach(e=>e())},notice:e=>sre(D(),y??Q8,e),running:()=>w(async()=>{let e=await ie(()=>v.read());return e.ok&&$8(e.value).kind===`running`}),error:()=>A,act:()=>w(async()=>{if(T)throw new qs(`apply-update`);let e=await ie(()=>v.read());if(T)throw new qs(`apply-update`);if(!e.ok)throw new R(`apply-update: ${e.error}`);let t=D();if(t===null)throw new R(`apply-update: nothing newer is known to apply`);let i=l5(t),a=e.value;if($8(a).kind===`running`)throw new R(`apply-update: already ${i.busy}`);let o=await are(r,s,a===null?null:a.act,s5(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new R(`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 pre(){return X.observable.box(so(`unread`),{deep:!1})}function u5(e,t){try{return F(t.statSync(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function mre(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function hre(e){let{targets:t,intervalMs:n,filesystem:r,held:i,exit:a,log:o,clock:s}=e,c=Fe(o),l=t.map(e=>({path:e,stamp:u5(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=u5(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!mre(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 gre=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 d5=`pass`,f5={okMs:5*6e4,failedMs:45e3},_re=f5.okMs;function p5({failures:e}){return kte(f5,e,_re)}function vre(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function yre(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function bre(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function xre(e,t,n,r){let i=[{path:n,filenames:[`HEAD`,`index`]},{path:s.join(r,`refs`,`heads`),recursive:!0}],a=i.map(t=>xc(e,t.path));return{key:`git:${t}:${i.map((e,t)=>`${e.path}@${Sc(a[t])}`).join(`|`)}`,targets:{dirs:i},unbound:a.some(e=>typeof e==`string`||`unreadable`in e)}}function Sre(e){return e.find(e=>e.kind===`ok`)?.value.branch}function m5(e){e.missed=!0,Vj(e,`unread`)}function Cre(e,t){return e.missed&&e.reading.get().kind===`pending`&&Bj(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function wre(e,t){let n=Wj(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:Wj(t)})}const Tre=L(`git cache closed`,`read`);function h5(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Ere=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 lo(e.maxPrLookups??2),this.logger=e.logger??Ie;let t=e.ledger??new tM(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 Fj({filesystem:Pn,clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`settled`)return Jj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>wre(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:Tre};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 gre,watch:this.followWatch(e,null).watch,period:new Lj(()=>{n.refresh.share(d5,()=>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=xre(this.watchers.filesystem,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(d5,()=>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&&m5(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(d5,()=>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:Rj(),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=bre(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(yre(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(h5(`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,Bj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of Fq(n.value))c.add(e)});let l=Sre(o),u=a===null||i.length===0?`-`:l===void 0?Cre(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}`,vre(n),c.size===0?F(null):L([...c].join(`; `),`read`),tt(this.clock,t))}prSource(e){let t={period:new Lj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:Rj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(h5(`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?(m5(t),`owed`):(Vj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Bj(t,a.outcome),t.period.landed(p5(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(h5(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(r)}`,n,i,tt(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||(Bj(t,i),t.period.landed(p5(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())Hj(n,t);e.pr!==null&&Hj(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()}};const g5={"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}},_5=new n(`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`);function Dre(e){let t=null;return{table:()=>e.closing.aborted?Promise.resolve(g5):t??=Ore(e).catch(t=>(e.log(`error`,`pricing load threw: ${String(t)}`),g5))}}const v5=e=>s.join(e,`usage`,`pricing.json`);async function Ore(e){let t=await kre(e);if(t!==null)return t;let n=e.closing.aborted?null:await jre(e.closing);return n===null?(Pe(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(g5).length} models`),g5):(e.closing.aborted||await Are(e,n),n)}async function kre(e){try{let t=JSON.parse(await h.promises.readFile(v5(e.cacheRoot),`utf8`));return typeof t.timestamp==`number`&&t.timestamp>=e.clock.now()-864e5&&y5(t.data)?t.data:null}catch(t){return t.code!==`ENOENT`&&e.log(`warn`,`pricing disk cache unreadable: ${String(t)}`),null}}async function Are(e,t){let n=v5(e.cacheRoot),r=`${n}.${process.pid}.${de()}`;try{await h.promises.mkdir(s.dirname(n),{recursive:!0}),await h.promises.writeFile(r,JSON.stringify({data:t,timestamp:e.clock.now()}),`utf8`),await h.promises.rename(r,n)}catch(t){e.log(`warn`,`pricing disk cache not written: ${String(t)}`),await h.promises.rm(r,{force:!0}).catch(()=>{})}}function jre(e){return new Promise(t=>{let n=ve({hostname:_5.hostname,path:_5.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3,agent:!1,signal:e},e=>{if(e.statusCode!==200){Pe(`HTTP ${e.statusCode}: ${e.statusMessage}`),e.resume(),t(null);return}let r=``,i=0;e.setEncoding(`utf8`),e.on(`data`,e=>{if(i+=Buffer.byteLength(e),i>1048576){Pe(`Response too large`),n.destroy(),t(null);return}r+=e}),e.on(`end`,()=>{try{let e=JSON.parse(r),n=e._meta,i={};for(let[t,n]of Object.entries(e))t!==`_meta`&&(i[t]=n);y5(i)?(Pe(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),Pe(`Pricing last updated: ${n?.updated||`unknown`}`),t(i)):(Pe(`Invalid pricing data structure`),t(null))}catch(e){Pe(`Failed to parse JSON:`,e),t(null)}}),e.on(`error`,e=>{Pe(`Response error:`,e),t(null)})});n.on(`error`,e=>{Pe(`Request error:`,e),t(null)}),n.on(`timeout`,()=>{Pe(`Request timeout`),n.destroy(),t(null)}),n.end()})}function y5(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`||typeof e.cache_write_5m!=`number`)return!1}return!0}function Mre(e,t){let n=t[e];if(n)return n;let r=e.toLowerCase();for(let[e,n]of Object.entries(t))if(e.toLowerCase()===r)return n;for(let{pattern:e,fallback:n}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=>r.includes(e))&&t[n])return t[n];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}}function Nre(e,t){let n=t.message?.usage;if(!n)return 0;let r=Mre(Pre(t),e),i=n.input_tokens||0,a=n.output_tokens||0,o=n.cache_creation_input_tokens||0,s=n.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}function Pre(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`}var b5=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 Fre(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 Ire={okMs:60*1e3,failedMs:10*1e3},x5={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function S5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function C5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const Lre={entries:0,cost:0,breakdown:C5(),days:new Map};async function Rre(e,t,n,r){let i=EX(new Date(S5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=null,l=new Map;for(let[t,n]of e.days)t>=i&&l.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let r=e.costUSD??Nre(c??=await n.table(),e.raw);o+=r,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=EX(new Date(e.timestamp));if(u<i)continue;let d=l.get(u)??{...wX};d.cost+=r,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,l.set(u,d)}return{entries:a,cost:o,breakdown:s,days:l}}function zre(e){let t=0,n=0,r=C5(),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)??{...wX};TX(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:x5,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 w5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function Bre(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!w5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...wX};TX(r,t),n.set(e,r)}return Object.fromEntries(n)}async function Vre(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 T5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function E5(e,t){(0,X.runInAction)(()=>e.set(t))}var Hre=class{sessions=X.observable.map(void 0,{deep:!1});flight=new b5;scans;daySets=new Map;speedFlight=new b5;requestFlight=new b5;staleAgeMs;host;pricing;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.pricing=e.pricing,this.clock=e.clock,this.log=e.logger??Ie,this.ledger=e.ledger??new tM(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new Xj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??Ire,watch:Yj,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=fo(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:F(T5(t.kind===`ok`?t.value.sessionInfo:x5,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 so(`unread`);let r=n.failure.get();return r===null?F(T5(n.record?.sessionInfo??x5,t)):L(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,tt(this.clock,i)),E5(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 Jj(L(`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`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||w5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return E5(this.hold(e).speed,t),t;let r=Fre(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=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return E5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??so(`unread`):I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,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),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+p),i={roots:r,sums:new nw(`today over ${e.join(`,`)}`,()=>Bre(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await J0(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of r2(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 i2(e,r,Lre,(e,t)=>Rre(e,t,this.pricing,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 r2(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...zre(i),mainStamp:a})}async scan(e){try{let t=S5(this.clock.now()),n=await K0(e),r=[];for(let e of n){let n=await q0(go(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await q0(_o(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:po(a)})}}let i=[],a={hits:0,misses:0};return await Vre(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?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=EX(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},D5=class{values=X.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,X.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},O5=class{sessions;flight=new b5;constructor(e,t,n,r,i=Ie,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new D5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=fo(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})}return this.flight.run(e,()=>this.fold(e,t,r))}async fold(e,t,n){let r=this.clock.monotonic(),i=await i2(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(e)}`,`request`,i,tt(this.clock,r)),i.kind===`failed`)return this.store(e,n,i);if(i.kind===`absent`)return this.store(e,n,{kind:`ok`,value:n?.value??this.empty});let{folded:a,longLines:o}=i.value;for(let e of r2(o))this.log(`info`,e);return this.store(e,a,{kind:`ok`,value:a.value})}answer(e){return this.sessions.get(e)?.answer??so(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function Ure(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 Wre=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(void 0,Ure,(e.ledger??new tM(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 Pe(`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);Pe(`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?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,k5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,k5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(Pe(`No main chain entries with usage data found`),I):(Pe(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function k5(e){return e.context_window?.context_window_size??2e5}const Gre={messageCount:0,nonPrompts:0,recent:[]},Kre=new Set([`turn`,`interrupt`,`claude-code`]);function qre(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!Kre.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function Jre(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 Yre=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(Gre,qre,(e.ledger??new tM(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){Pe(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?A5(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:A5(e,n,r)}};function A5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`,n.failedAt):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:Jre(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 Xre={command:null,todos:[],pending:[],done:[]};function j5(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 Zre(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 Qre(e,t){if(t.isSidechain)return e;let n=Zre(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=j5(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 $re(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>j5(e,t.name),[]),done:e.done}}var eie=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(Xre,Qre,(e.ledger??new tM(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`?L(`activity (${e}): ${t.reason}`,t.failedAt):F($re(t.value))}const N5=3e4;var tie=class{names;constructor(e){let t=e.logger??Ie;this.names=new Xj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>nie(e.launcher,t),every:()=>({okMs:N5,failedMs:N5}),watch:Yj,maxEntries:64,logger:t,ledger:e.ledger??new tM(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function nie(e,t){let n=await Ws(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const P5=6e4,rie={okMs:P5,failedMs:P5};function iie(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function F5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var aie=class{name;user;constructor(e){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>rie,watch:Yj,maxEntries:1,logger:t,ledger:e.ledger??new tM(t),clock:e.clock};this.name=new Xj({...n,name:`host.name`,read:()=>F5(`name`,()=>iie(o.hostname()))}),this.user=new Xj({...n,name:`host.user`,read:()=>F5(`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()}},oie=class{known=new D5(64);refreshes;constructor(e,t=Ie,n=new tM(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=sie(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=NI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,tt(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??so(`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 sie(e){try{let t=h.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:po(t)}catch(e){return`unread:${e.code??`error`}`}}const cie=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function lie(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 uie=class{known=new D5(256);refreshes;constructor(e,t=Ie,n=new tM(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=fo(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??so(`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 die(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,tt(this.clock,r)),i}};async function die(e){let t=await fie(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function fie(e){for(let t of[65536,1048576]){let n=await Eo(e,t);if(n.kind!==`ok`)return n;let r=pie(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function pie(e,t){let n=e.toString(`utf8`).split(`
|
|
499
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!cie.test(t))continue;let r=lie(t);if(r!=null)return r}return null}const I5=e=>sH(e),L5=e=>s.join(e.storage.folder,I5(e.sessionId)),R5=e=>JSON.stringify([e.folder,e.generation]),z5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var mie=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new Xj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(L5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Yj,maxEntries:256,logger:e.logger,ledger:e.ledger??new tM(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{this.watchers.filesystem.mkdirSync(e),n=vc(this.watchers.filesystem,e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!yc(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(R5(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?vc(this.watchers.filesystem,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:${R5(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(R5(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=R5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>z5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(s.join(n.folder,s.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(L5(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=vc(this.watchers.filesystem,r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&yc(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=>z5(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=>z5(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(R5(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=Ac(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=L5(e),r;try{r=await this.watchers.filesystem.readFile(n)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=sM(r);return i.kind===`failed`?L(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${z(e.folder)} scanned=${r} removed=${i} took=${tt(this.clock,t)}ms`;try{let t=await this.watchers.filesystem.readdir(e.folder);for(let a of t){if(a.kind!==`file`||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await this.watchers.filesystem.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&I5(t.sessionId)===a.name);if(r>=n||o)continue;await this.watchers.filesystem.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 hie(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new aie({clock:n,logger:r,ledger:i}),gitProvider:new Ere({inner:new lJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new Hre({host:e.host,pricing:e.pricing,clock:n,logger:r,ledger:i}),contextProvider:new Wre({clock:n,logger:r,ledger:i}),metricsProvider:new Yre({clock:n,logger:r,ledger:i}),activityProvider:new eie({clock:n,logger:r,ledger:i}),tmuxService:new tie({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new oie(n,r,i),cacheExpiry:new uie(n,r,i),managedStorage:new mie({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new jX,log:e.logger,clock:n}}function*B5(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*gie(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 Fx(e.presets)){for(let n of $v(Rx(e,t).node))n.when!==void 0&&(yield n.when);let n=Bx(e,t);for(let e of pv){let t=n[e];mv(t)&&(yield t)}}for(let[,t]of B5(e))for(let[,e]of cy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Yx(t))yield e}function _ie(e,t,n){let r=XK(t),i=new Set,a=new Set,o=new Set;for(let e of gie(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of DC(e,t.helpers))a.add(n);for(let n of PC(e,t.helpers))o.add(n)}for(let[,e]of B5(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 Fx(t.presets))for(let n of $v(Rx(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=>!rS(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(B5(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 vie(e){return Math.floor(Math.max(e/4,e*xi-67108864))}const yie={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function V5(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[oH(rC(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[rC(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>iC(e)(t)&&t!==oH(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${MP(e,`<default>`)}: projections=${[...eq(n).keys()].join(`,`)||`-`} instantSegments=${vq(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 bie=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},xie=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${bie(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Sie(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.projectDir)} cwd=${z(e.cwd)} cause=${z(xie(t))} state=${n} files=${z(MP(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 Cie(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function wie(e,t,n){return e+`\0`+t+`\0`+(n??``)}function Tie(e,t){return new Set(Fx(e.presets).filter(n=>Rx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Eie(e,t,n){let{loaded:r,dropped:i,unreached:a}=t.state.plugins,o=[...new Set([...t.state.plugins.roots,s.join(t.projectDir,BH)])];return Oj(e,{named:[...eU(n,t.projectDir,t.cwd,t.configFile),...o,...r.map(e=>e.path),...[...i,...a].map(e=>e.path),...new Set([...t.state.sources.values()].map(e=>e.folder))],whole:o})}function Die(e){return e.filter(Boolean).join(`
|
|
500
|
-
`)||null}const H5=e=>e instanceof Error?e.message:String(e);function U5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Oie(e){let{loaded:t,chain:n}=e;return Gv({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:U5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...U5(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 kie(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 W5(e,t,n){let r=[];try{let i=YY(t.locs,t.layers,xX,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:kie(i.config,n)};return{kind:`resolved`,...a,key:Oie(a),warnings:r}}catch(e){return e instanceof Ty&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function G5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??xX,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new fw(t.clock),m=new jM(yM,p,o.globals.default_empty_value??``,t.sessionState),h;try{h=fq(o,m,n,t.compile??dq(t.links),jie),f.push(...h.loadWarnings);let r=m.view(vM);f.push(...hq(o,r,n,Y5)),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 Ty&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:Tie(l,u),fileHeldSettings:h$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>_ie(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 K5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:tt(i,e.started)},o=t=>Die([...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:H5(r.cause),cause:r.cause}}}function Aie(e,t,n,r,i=null){let a=W5(t,n,r.storage);if(a.kind===`failed`)return K5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:G5(a,r);return K5(e,n,a.warnings,o,r.clock)}function q5(e,t,n,r,i=null){let a=r.clock.monotonic(),o=iU(r.locations,HU(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 Aie({repos:s,advisories:[dU(r.locations,e,t),lU(o),ZH(s)],started:a},t,c,r,i)}function J5(e,t,n){let r=W5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:G5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${H5(i.cause)}`,{cause:i.cause});return i.state}const jie=new Set([`directory`]),Y5=new Set([`view`]);function Mie(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c={sources:e.sources},l=r.follow(n,c),u=e.registry.view(l.runs),d=X.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,X.runInAction)(()=>{l.follow(e,c),d.set({facts:e})})},p=[],m=()=>(0,X.runInAction)(()=>{for(let e of p)e();let e=u.dispose();return l.dispose(),e});try{hq(e.config,u,t,Y5)}catch(e){throw m(),e}let h;try{h=i({sessionId:s,state:e,store:u.variableStore,declared:()=>d.get(),followed:l,onDispose:e=>p.push(e)})}catch(e){throw m(),e}EK(e.compiled,u.variableStore,u,h);let g=(0,X.reaction)(()=>[h.payload(),h.selections(),u.published()],()=>a(s),{equals:X.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:u.variableStore,registry:u,source:h,requested:f,facts:()=>d.get().facts,settle:e=>l.settle(e),followed:{stamped:l.stamped,failure:l.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var Nie=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??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},e.watchers.filesystem.mkdirSync(BU(e.stateDir));let{dir:n,name:r}=Ej(e.watchers.filesystem,VU(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)??_q(t,this.deps.links)}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=wie(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`,V5(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??J5(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=${P(this.accountedBytes())}/${P(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.placeView(i,a),a.requested(n),a;this.placeView(i,void 0);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=Mie(t,e.cwd,n,{facts:this.deps.facts,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.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.placeView(a,o),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}placeView(e,t){let n=this.views.get(e);this.views.delete(e),t!==void 0&&this.views.set(e,t),t!==n&&this.observers.onSessionViewMoved?.(e)}sessionView(e){return this.views.get(e)??null}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.placeView(e.sessionId,void 0),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 q5(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=${P(this.accountedBytes())}/${P(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`,Cie(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`,V5(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=Eie(this.deps.watchers.filesystem,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 Pie=e=>!K1(e)&&!xI(e)&&e!==`update.dismissed`&&e!==sS;var Fie=class{past=X.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:j1(e,Pie,(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 R(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,X.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const X5=(e,t)=>e.kind===`ok`?F(t(e.value)):e;function Iie(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest??so(`unread`)}}const Z5=(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 Lie({pullRequest:e,...t}){return t}function Q5(e,t,n,r,i){let{lanes:a}=n,o=a.git,s=(e,t)=>GZ(e,t,i),c=e?.builtins,l={session:s(c?.session,a.usage),today:s(c?.today,n.today),speed:s(c?.speed,a.speed),context:s(c?.context,a.context),metrics:s(c?.metrics,a.metrics),activity:s(c?.activity,a.activity),cache:s(c?.cache,a.cache),autocompact:s(c?.autocompact,a.autoCompact),git:s(c?.git,X5(o,Lie)),pr:s(c?.pr,Iie(o)),tmux:s(c?.tmux,X5(a.tmuxSession,e=>({session:e}))),hostName:s(c?.hostName,a.hostName),hostUser:s(c?.hostUser,a.hostUser)},u=Object.fromEntries([...a.sources].map(([t,n])=>[t,s(e?.sources[t],n)])),d=Object.fromEntries([...n.runs].map(([t,{reading:n,fault:r}])=>{let i=e?.runs[t],a=s(i?.reading,n);return[t,i!==void 0&&i.reading===a&&i.fault===r?i:{reading:a,fault:r}]})),f={builtins:l,sources:u,runs:d,update:r,diagnostics:n.faults};return e!==void 0&&Z5(l,e.builtins)&&Z5(u,e.sources)&&Z5(d,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:2,session:t,seq:e===void 0?1:e.seq+1,...f}}function Rie(e,t,n){let r=cM(e),i=(0,X.computed)(()=>t().runs[r]),a=(0,X.computed)(()=>{let e=i.get();return e===void 0?n(r):$X(e.reading)},{equals:X.compareStructural});return{digest:r,current:()=>a.get(),fault:()=>i.get()?.fault??null}}function zie(e,t,n,r){if(t.kind===`failed`)return io(e,t.reason);try{let i=Q5(e.line.facts,r,t.readings,t.update,n),a=i===e.line.facts?e.line:{at:n,facts:i};return a===e.line&&e.failure===null?e:{line:a,failure:null}}catch(t){return io(e,`stamping the facts document: ${String(t)}`)}}function Bie({providers:e,update:t,runs:n}){let{clock:r,log:i}=e;return{follow(a,o){let s=a.sessionId,c=new Tj,l=X.observable.map(void 0,{deep:!1}),u=!1,d=(e,t)=>{if(!l.has(t))return L(`the run of ${uM(e.read)} is not declared by this view`,`read`);let{failure:n}=y.get();return n===null?so(`unread`):L(`the run of ${uM(e.read)} is in no document: ${n}`,`read`)},f=JSON.stringify(s),p=(t,{sources:n})=>{try{let{result:{lanes:r,faults:a},acquired:o,released:s}=c.declare(()=>JX(e,c,t,n));for(let e of a)i(`error`,`session view declaration threw sid=${f} ${e}`);return o+s>0&&i(`info`,`session view declared sid=${f} acquired=${o} released=${s} held=${c.size}`),r}catch(e){return i(`error`,`session view declaration threw sid=${f}: ${k(e)}`),GX(L(`view declaration threw: ${String(e)}`,`read`),[...n.keys()])}},m=X.observable.box({facts:a,lanes:p(a,o)},{deep:!1}),h=(0,X.computed)(()=>{let{facts:t}=m.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>m.get().lanes}}}),g=(0,X.computed)(()=>YX(h.get())),_=(0,X.computed)(()=>new Map([...l].map(([e,{run:t}])=>[e,{reading:t.current(),fault:t.fault()}]))),v=(0,X.computed)(()=>({...g.get(),runs:_.get()})),y,b=(0,X.reaction)(()=>{try{return{kind:`read`,readings:v.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,X.runInAction)(()=>{let t=y.get(),n=zie(t,e,ut(r),s);n.failure!==null&&n!==t&&i(`error`,`session facts sid=${f}: ${n.failure}`),y.set(n)}),{onError:e=>i(`error`,`session facts threw sid=${f}: ${k(e)}`)});try{let e=ut(r);y=X.observable.box({line:{at:e,facts:Q5(void 0,s,v.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw b(),c.close(),e}return{runs:{declare:(e,t)=>{if(u)throw Error(`the run of ${uM(t.read)} was declared after its view's follow was disposed`);let r=cM(t);return e.take(`facts.run:${r}`,()=>{let e=new Tj,i=n.declare(e,t),a=Rie(t,()=>y.get().line.facts,e=>d(t,e));return(0,X.runInAction)(()=>l.set(r,{run:i,held:e,lane:a})),()=>{(0,X.runInAction)(()=>l.delete(r)),e.close()}}),l.get(r).lane}},stamped:()=>y.get().line,failure:()=>y.get().failure,follow:(e,t)=>{let n=p(e,t);(0,X.runInAction)(()=>m.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:sZ(h.get(),e,t)}},dispose:()=>{u=!0,b();for(let{held:e}of l.values())e.close();c.close()}}}}}function $5(e,t){return e===t||e?.cause===t?.cause&&e?.reason===t?.reason}function Vie(e,t,n){if(t.kind===`failed`){let n={cause:`inputs`,reason:t.reason};return $5(e.failure,n)?e:{...e,failure:n}}let r=t.facts===null?null:{cause:`facts`,reason:t.facts};return $5(e.failure,r)&&t.stamped===e.stamped&&t.request===e.request&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,request:t.request,picks:n(),compose:t.compose,draw:t.draw,failure:r}}function Hie(e){return({sessionId:t,state:n,store:r,declared:i,followed:a,onDispose:o})=>{let s=n=>e.sessionState.get(t,n),c=r.derive(`session.effective`,`computed`,()=>bZ(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),u=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...g$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),d=()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t)}),f=a.failure(),p=X.observable.box({stamped:a.stamped(),request:i().facts,picks:d(),compose:l.read(),draw:u.read(),failure:f===null?null:{cause:`facts`,reason:f}},{deep:!1});o((0,X.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),request:i().facts,compose:l.read(),draw:u.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,X.runInAction)(()=>{let r=p.get(),i=Vie(r,n,d);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${n.reason}`),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{stamped:e,compose:t,draw:n}=p.get();return eZ(e.facts,t,n)});return{payload:()=>m.read(),effective:()=>p.get().draw.effective,facts:()=>p.get().stamped.facts,turn:()=>{let{stamped:e,request:t,picks:n,draw:r}=p.get();return{document:e,request:t,state:{...n,history:r.history,back:r.back}}},held:()=>p.get().failure?.cause===`inputs`,home:()=>p.get().compose.home,hints:()=>p.get().compose.hints,failure:()=>p.get().failure,selections:()=>p.get().draw.effective,state:()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t),history:p.get().draw.history,back:p.get().draw.back})}}}const Uie=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function e7(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?Uie[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const Wie={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 Gie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=e7(t),o=e7(n),s={};for(let e of r){let t=Wie[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 Kie(e){return{ok:!0,band:e.rows.map(e=>$P(e).map(Gie))}}function qie(e){return YP(Kie,e)}const Jie=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function t7(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:Jie[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 Yie={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 Xie(e){return e.replaceAll(`#`,`##`)}function Zie({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=Yie[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${t7(e)}`,`bg=${t7(t)}`,...r].join(`,`)}]`}function Qie(e,t){let n={},r=e=>{let r=Zie(e)+Xie(e.text);if(e.link===void 0)return r;let i=t(e.link);return i===null?r:(n[i]=e.link,`#[range=user|${i}]${r}#[norange]`)};return{rows:e.rows.map(e=>$P(e).map(r).join(``)),links:n}}function $ie(e,t){return t.frame(t=>YP(e=>Qie(e,t),e))}var eae=class{ranges=new Map;constructor(e,t=256){this.source=e,this.cap=t}frame(e){let t=new Set,n=e(e=>(t.add(e),this.rangeOf(e)));for(let e of this.ranges.keys()){if(this.ranges.size<=this.cap||t.has(e))break;this.ranges.delete(e),this.source.evicted()}return n}rangeOf(e){let t=this.ranges.get(e);if(t!==void 0)return this.ranges.delete(e),this.ranges.set(e,t),this.source.reused(),t;let n=this.source.next();if(n===null)return null;let r=`ccb`+n.toString(36);return this.ranges.set(e,r),r}};function tae(e){return{band:()=>e=>({json:JSON.stringify(qie(e)),value:null}),statusline:()=>(e,t)=>({json:t,value:null}),pane:()=>(e,t)=>({json:t,value:null}),tmuxStatus:()=>{let t=new eae(e);return e=>{let n=$ie(e,t);return{json:JSON.stringify({ok:!0,tmuxStatus:n}),value:n}}}}}const nae=/^\d{1,15}\n?$/,rae=10**15-1,n7=`remove it and a new one is made, starting again from 0 (a click on a status row drawn before then may run a link drawn since)`;function iae(e){let{file:t,clock:n,retryMs:r,log:i}=e,a=0,o={kind:`ready`,next:0},s=0,c=0,l=0,u=0,d=0,f=()=>{try{let e=Math.max(aae(t),a),n=e+1024;if(n>rae)throw Error(`${t} holds ${e}, too near the last count for another block: ${n7}`);return dr(t,`${n}\n`,384),a=n,u++,o.kind===`faulted`&&i(`info`,`link ids: ${t} reserved again`),{kind:`ready`,next:e}}catch(e){d++;let t=`link ids: ${e.message}`;return(o.kind!==`faulted`||o.reason!==t)&&i(`error`,t),{kind:`faulted`,reason:t,clear:n.after(r,()=>o=f(),{unref:!0})}}};return{next(){return o.kind===`ready`&&o.next===a&&(o=f()),o.kind===`ready`?(s++,o.next++):null},reused:()=>void c++,evicted:()=>void l++,error:()=>o.kind===`faulted`?o.reason:null,stats:()=>({minted:s,reused:c,evicted:l,reservations:u,faults:d}),close(){o.kind===`faulted`&&o.clear(),o={kind:`closed`}}}}function aae(e){let t;try{t=h.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return 0;throw e}if(!nae.test(t))throw Error(`${e} holds ${JSON.stringify(t.slice(0,40))}, not a count: ${n7}`);return Number(t.trim())}const r7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,i7=`#{session_id} #{client_control_mode} #{pane_id}`;function a7(e){let t=new Set;for(let n of e.split(`
|
|
495
|
+
`}const X4=e=>({kind:`ok`,value:e}),Z4=e=>({kind:`failed`,reason:e});var Q4=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const $4=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function e3(e){return $4.test(e)?e:null}function t3(e,t){let n=e.opener(t);if(n.kind===`failed`)return n;if(n.value===null)return X4(null);let r=n.value;return X4({app:r,forwarder:e.exists(ls(r))})}async function n3(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 r3(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}; the URL handler delivers a link naming ${e.name} 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=US(e.name,n),i=e.open(r);return(i===null?await n3(e,n):null)??{kind:`lost`,unopened:i,opener:t3(e,r),otherBuild:t.value.otherBuild}}function i3(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?X4(i.stdout):Z4(vt(i))}const a3=e=>`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString(${JSON.stringify(e)}));u.isNil() ? "" : u.path.js`;async function o3(e){let t=await L4(e);if(t.kind!==`ok`)return Z4(Jr(t).split(`
|
|
496
|
+
`).join(` — `));let n=R4(t.value,[`handlerProbes`]);if(n!==null)return Z4(n);let r=[];for(let e of t.value.handlerProbes){let t=s3(e);if(t===null)return Z4(`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 X4({arrivals:r,otherBuild:z4(t.value)})}function s3(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 c3(e,t){let{home:n,clock:r}=t;return{platform:process.platform,name:n.name,sockets:{own:Vn(n),handler:Hn(n.name)},monotonic:()=>r.monotonic(),nonce:de,daemon:()=>o3(t),open:t=>{let n=i3(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>rt(r,100),opener:t=>{let n=i3(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,a3(t)]);if(n.kind===`failed`)return n;let r=n.value.trim();return X4(r===``?null:r)},exists:h.existsSync}}function l3(e){return Xs(()=>decodeURIComponent(e))}const u3=5e3;function d3(e,t,n){if(e.reason===`rate-limited`){n(`warn`,vt(e));return}throw e.reason===`aborted`?new qs(t):Error(`${t} failed (${vt(e)})`)}async function f3(e,t,n,r,i,a){let o=S(s.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:s.join(o,`stderr`),status:s.join(o,`status`)},c=e.launchJobSync(t,a);if(!c.ok){d3({...c,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}c.release();let l=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(c.pid),s=Yt(a.status);if(s!==null){if(s.kind===`exit`&&s.code===0)return;d3(s.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:w(a.stderr,`utf8`),exitCode:s.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()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await rt(e.clock,50)}}finally{E(o,{recursive:!0,force:!0,maxRetries:3})}}function p3(e,t){m3(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function m3(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const h3=(e,[t=``],n)=>{p3(t,n)},g3=new Set([`request`,`feed`]);function _3(e){if(!g3.has(e))throw new R(`unknown renderer ${JSON.stringify(e)}`);return e}const v3=(e,t,n)=>{let[r=``,i=``]=t,a=n.diagnosticCopy(e,_3(r),i);if(a===void 0)throw new R(`that message is no longer listed in session ${e}'s diagnostics — open ⚠ again and copy from there`);p3(a,n)},y3=(e,[t=``],n)=>{m3(n,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t],category:`click.open`},`open -a "Visual Studio Code"`)},b3=(e,t,n)=>{n.navigating.get(e,`toolbar-expanded`)?n.navigating.clear(e,`toolbar-expanded`):n.navigating.set(e,`toolbar-expanded`,`1`)},x3=(e,t,n)=>{let r=n.gates.state.gateFor(N3(n,e));if(t.length===0)throw new R(`set-state: <key>/<value> is required (have keys: ${r.listKeys().join(`, `)})`);if(t.length%2!=0)throw new R(`set-state: expected even-count <key>/<value> pairs, got ${t.length} segment(s) after session id (have keys: ${r.listKeys().join(`, `)})`);let i=[];for(let e=0;e<t.length;e+=2){let n=t[e],a=t[e+1];if(!n)throw new R(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let o=r.validate(n,a);if(!o.ok)throw new R(`set-state: pair ${e/2+1}: ${o.reason}`);i.push({key:n,value:o.value})}T3(n,e,`set-state`,i),n.navigating.setBatch(e,i);let a=i.map(e=>`${e.key}=${e.value}`).join(` `);n.log(`info`,`set-state: ${a} (session=${e})`)},S3=/^-?\d+$/;function C3(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const w3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!S3.test(i))throw new R(`step-state: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=N3(n,e),s=n.gates.state.gateFor(o),c=s.rangeParamsFor(r);if(!c)throw new R(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${s.listKeys().join(`, `)})`);let l=n.sessionState.get(e,r),u=l&&S3.test(l)?E3(c,parseInt(l,10)):D3(`step-state`,r,c,y$(o,t=>n.sessionState.get(e,t),r)),d=C3(u,a,c.min,c.max),f=s.validate(r,String(d));if(!f.ok)throw new R(`step-state: ${f.reason}`);T3(n,e,`step-state`,[{key:r,value:f.value}]),n.navigating.set(e,r,f.value),n.log(`info`,`step-state: ${r} ${u}→${f.value} (by ${a}, session=${e})`)};function T3(e,t,n,r){let i=r.filter(e=>e.key.startsWith(sP));if(i.length===0)return;let a=c$(N3(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new R(`${n}: refused — ${a.join(`; `)}`)}function E3(e,t){return Math.max(e.min,Math.min(e.max,t))}function D3(e,t,n,r){if(r===null)return n.min;if(!S3.test(r))throw new R(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return E3(n,parseInt(r,10))}function O3(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function k3(e,t){let n;try{n=JSON.parse(e)}catch{throw new R(`render origin is not JSON: ${e}`)}if(typeof n!=`object`||!n)throw new R(`render origin is not an object: ${e}`);let{projectDir:r,cwd:i,configFile:a,source:o}=n;if(typeof r!=`string`||typeof i!=`string`||a===void 0)throw new R(`render origin has the wrong shape: ${e}`);let s;try{s=a===null?null:H1(t,a)}catch(e){throw e instanceof V1?new R(`render origin: ${e.message}`):e}return{projectDir:r,cwd:i,target:O3(o,s)}}function A3(e,t){let n=j3(e,t);if(n===null)throw new R(`session ${t} has not rendered yet — no config to act on`);return n}function j3(e,t){let n=e.sessionState.get(t,KQ);return n===null?null:k3(n,e.storedRoot)}function M3(e,t,n){let r=j3(e,t);if(r===null)return;let{path:i}=I3(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function N3(e,t){return e.configFor(A3(e,t))}function P3(e,t){let n=j3(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function F3(e,t){let n=j3(e,t);return n===null?x$:T$(e.configFor(n))}function I3(e,t){return iU(e.locations,RU(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 R3=(e,t,n)=>{let[r=``,i=``]=t,a=A3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`set-config: <key>/<value> is required (have keys: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`set-config: ${c.reason}`);let l=I3(n,a),u=o$(o,t=>n.sessionState.get(e,t),r);_1(L3(n,e),l,[[u.key,c.value]]),n.reloadConfig(a),n.log(`info`,`set-config: ${u.key}=${c.value} → ${l.path} (session=${e})`)},z3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!S3.test(i))throw new R(`step-config: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=A3(n,e),s=n.configFor(o),c=n.gates.config.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new R(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${c.listKeys().join(`, `)})`);let u=I3(n,o),d=o$(s,t=>n.sessionState.get(e,t),r),f=g1(u.path,d.key),p=typeof f==`number`?E3(l,f):D3(`step-config`,r,l,b$(d.globals,r)),m=C3(p,a,l.min,l.max),h=c.validate(r,String(m));if(!h.ok)throw new R(`step-config: ${h.reason}`);_1(L3(n,e),u,[[d.key,h.value]]),n.reloadConfig(o),n.log(`info`,`step-config: ${d.key} ${p}→${h.value} (by ${a}) → ${u.path} (session=${e})`)},B3=(e,t,n)=>{let r=A3(n,e),i=n.configFor(r),a=t=>n.sessionState.get(e,t),o=i$(i,a),s=s$(i,a);if(o.length+s.length===0){n.log(`info`,`save: nothing unsaved (session=${e})`);return}let c=n.gates.state.gateFor(i),l=o.map(e=>{let t=c.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save: ${t.reason}`);return[e.target,t.value]});H3(`save`,c,s);let u=I3(n,r);v1(L3(n,e),u,l,s),n.reloadConfig(r);for(let t of[...o.map(e=>e.sessionKey),...s.map(e=>e.key)])n.sessionState.clear(e,t);n.log(`info`,`save: ${[...l.map(([e,t])=>`${e}=${t}`),...s.map(V3)].join(` `)} → ${u.path} (session=${e})`)},V3=e=>`${e.preset}/${e.id}.settings.${e.setting}=${_y(e.value)}`;function H3(e,t,n){for(let r of n){let n=t.validate(r.key,_y(r.value));if(!n.ok)throw new R(`${e}: ${n.reason}`)}}const U3=(e,t,n)=>{let r=A3(n,e),i=n.configFor(r),a=d$(i,t=>n.sessionState.get(e,t)),o=n.gates.state.gateFor(i),s=a.picks.map(e=>{let t=o.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save-preset: ${t.reason}`);return[e.configKey,t.value]});H3(`save-preset`,o,a.placements);let c=I3(n,r),l=T1(L3(n,e),c,a.from,a.globals,s,a.placements);n.reloadConfig(r);for(let t of[...ix.map(e=>e.sessionKey),...a.placements.map(e=>e.key)])n.sessionState.clear(e,t);n.sessionState.set(e,nx.preset.sessionKey,l),n.log(`info`,`save-preset: ${[`${l} from=${a.from}`,...s.map(([e,t])=>`${e}=${t}`),...a.placements.map(V3)].join(` `)} → ${c.path} (session=${e})`)},W3=(e,t,n)=>{let r=A3(n,e),i=p$(n.configFor(r),t=>n.sessionState.get(e,t));if(i.kind===`rule`)throw new R(`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 a=I3(n,r);E1(L3(n,e),a,i.theme,i.look),n.reloadConfig(r);let o=new Set(i$(n.configFor(r),t=>n.sessionState.get(e,t)).map(e=>e.sessionKey)),s=Zb.map(e=>nx[e].sessionKey).filter(e=>!o.has(e));for(let t of s)n.sessionState.clear(e,t);n.log(`info`,`save-theme-default: ${i.theme} ${Zb.map(e=>`${e}=${i.look[e]}`).join(` `)} → ${a.path} (session=${e})`)},G3=(e,t,n)=>{let[r=``]=t;if(!r)throw new R(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let i=A3(n,e),a=I3(n,i);D1(L3(n,e),a,r),n.reloadConfig(i);let o=nx.preset.sessionKey;n.sessionState.get(e,o)===r&&n.sessionState.clear(e,o),n.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${e})`)},K3=(e,t,n)=>{let r=t,i=A3(n,e),a=n.gates.config.gateFor(n.configFor(i)).listKeys(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new R(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=I3(n,i),c=r.map(m$),l=c.flatMap(e=>e.fileKeys),u=c.flatMap(e=>e.sessionKeys);S1(L3(n,e),s,l),n.reloadConfig(i);for(let t of u)n.sessionState.clear(e,t);n.log(`info`,`reset-config: ${[...l,...u.map(e=>`session:${e}`)].join(` `)} ← ${s.path} (session=${e})`)};function q3(e,t){let n=(e,t)=>[...Zv(Fx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Mx(t.presets).flatMap(e=>n(t,e).map(t=>cP(BM(e),qv(t)))));return Mx(e.presets).flatMap(t=>n(e,t).map(e=>({member:cP(BM(t),qv(e)),node:e})).filter(({member:e})=>!r.has(e)))}function J3(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[iP]:[]])}const Y3=(e,t,n)=>{let[r=``,i=``]=t,a=A3(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`apply-layout-op: <key>/<op> is required (have: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`apply-layout-op: ${c.reason}`);let l=$R(c.value);if(l===null)throw new R(`apply-layout-op: "${c.value}" is not a layout op token`);let u=I3(n,a),d=O1(L3(n,e),u,r,l);n.reloadConfig(a);let f=J3(q3(o,n.configFor(a)),n.sessionState.get(e,iP)).filter(t=>n.sessionState.get(e,t)!==null);for(let t of f)n.sessionState.clear(e,t);n.log(`info`,`apply-layout-op: ${r} ${c.value} → ${u.path} placed=${JSON.stringify(d)} released=${JSON.stringify(f)} (session=${e})`)},X3=(e,t,n)=>{n.journal.commit();let r=n.history.undo(e);n.journal.wrote(),M3(n,e,r),n.log(`info`,`undo: restored ${u0(r)} (session=${e})`)},Z3=(e,t,n)=>{let{step:r,discarded:i}=n.navigation.back(e,n.sessionState,n.gates.state.gateFor(N3(n,e))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);n.log(`info`,`back: ${a} discarded=${i} (session=${e})`)},Q3=(e,t,n)=>{n.journal.commit(),n.journal.wrote();let r=n.history.rewind(e);M3(n,e,r),n.log(`info`,`rewind: put back ${u0(r)||`nothing`} as edit mode found it (session=${e})`)},$3=(e,t,n)=>{n.journal.commit();let r=n.history.redo(e);n.journal.wrote(),M3(n,e,r),n.log(`info`,`redo: re-applied ${u0(r)} (session=${e})`)},e6=(e,t,n)=>{n.effect({kind:`apply-update`})};function t6(e,t){let n=e.sessionState.get(t,qQ);if(n===null)throw new R(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new R(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new R(`client hints record is not an object: ${n}`);return yr(r)}function n6(e,t,n){let r=JF(n);e.sessionState.setBatch(t,dI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${QF(n.config)} ${lI(n.nerdFont,n.marks)} ${$F(n.terminal,n.clicked)} ${eI(n.terminal,n.width)} ${tI(n.install)} ${rI(n.daemon)} ${iI(n.data)} ${cI(n.transcripts)} ${aI(n.frames,n.claudeSettings)} ${sI(n.claudeSettings.origin.sources)} (session=${t})`)}function r6(e,t,n){e.effect({kind:`doctor`,session:t,step:n,arrival:e.arrival})}function i6(e,t){let n=e=>{throw Error(`doctor: the gather ${e}; a gather writes nothing`)};return{get:(n,r)=>{let i=e.get(n,r);return t.set(JSON.stringify([n,r]),{what:r,value:i,again:e=>e.get(n,r)}),i},values:()=>n(`read every key; a gather reads keys by name`),revision:t=>e.revision(t),set:(e,t)=>n(`set ${t}`),setBatch:()=>n(`wrote a batch`),clear:(e,t)=>n(`cleared ${t}`)}}function a6(e,t,n){for(let{what:t,value:r,again:i}of n.reads)if(i(e.sessionState)!==r)return t;let r=e.doctor.loadConfig(A3(e,t));return r.config===n.load.config&&r.error===n.load.error&&r.warning===n.load.warning?null:`config`}function o6(e,t){let{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}=t6({sessionState:e},t);return{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}}async function s6(e,t,n,r){let i=new Map,a={...e,sessionState:i6(e.sessionState,i)},o=e=>JSON.stringify(o6(e,t)),s=o6(e.sessionState,t);i.set(`hints`,{what:qQ,value:JSON.stringify(s),again:o});let c=r.loadConfig(A3(a,t)),l={kind:`clicked`,sessionId:t,via:n.via},u=e.clients.ofSession(t,e.now()),d;try{d=await k4({...r,loadConfig:()=>c},s,A3(a,t),e=>a.sessionState.get(t,e),{kind:`ok`,value:e.serving()},{kind:`ok`,value:u.map(e=>e.rateLimits)},{kind:`ok`,value:u.map(e=>e.transcript)},l,{kind:`ok`,value:M0(l,u)},O4(t,u),t4(e.doctorStores))}catch(e){throw e instanceof O0?new R(e.message):e}return{facts:d,install:$2(r.install,e.bundle,u.map(e=>e.client)),stamp:{load:c,reads:[...i.values()]}}}async function c6(e,t){let n=n4(e.doctor),r=t.session;return e.journalTurns.gathering(async()=>{let i=await s6(e,r,t.arrival,n);return a6(e,r,i.stamp)===null?i:s6(e,r,t.arrival,n)})}function l6(e,t,n,{facts:r,install:i}){let a=t4(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:T4(n),install:i,clicked:u6(e,n,o)}}function u6(e,t,{terminal:n,clicked:r}){let i=n.kind===`seen`?vF(n.identified):null;if(i===null||t.via!==`link`)return r;try{return e.doctorStores.clicked.update(e=>E0(e,i))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(i)}: ${t instanceof Error?t.message:String(t)}`),r}}const d6={run:(e,t,n,r)=>n6(e,t,r),fix:(e,t,{check:n},r)=>{let i=n.probe(r);if(i.ok||i.fix===void 0)throw new R(`doctor-fix: ${n.label} — ${i.ok?`nothing to fix`:i.reason}`);let a=A4(e.doctorStores,i.fix,r);if(a.kind===`failed`)throw new R(`doctor-fix: ${n.label} — ${a.reason}`);e.log(`info`,`doctor-fix: ${n.name} → ${Pne(i.fix)} (session=${t})`),n6(e,t,a.value)},mark:(e,t,{check:n,mark:r},i)=>{let a=n.probe(i);if(a.ok||a.sighting===void 0)throw new R(`doctor-mark: ${n.label} — ${a.ok?`nothing to mark`:`shows nothing to look at`}`);let o=e.doctorStores.marks.update(e=>C0(e,n.name,a.sighting.id,r));if(o.kind===`failed`)throw new R(`doctor-mark: ${o.reason}`);e.log(`info`,`doctor-mark: ${n.name} ${r} on ${a.sighting.id} (session=${t})`),n6(e,t,{...i,marks:o})}};function f6(e,t,n){let r=t.session,i=a6(e,r,n.stamp);if(i!==null)throw new R(`doctor: the session's ${i} changed during the doctor's probes — click again`);p6(e,r,t.step,l6(e,r,t.arrival,n))}function p6(e,t,n,r){let i=d6[n.kind];i(e,t,n,r)}const m6=(e,t,n)=>{r6(n,e,{kind:`run`})},h6=(e,t)=>{let n=e3(l3(e));if(n===null)throw new R(`probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new R(`probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`probe: arrived nonce=${n} delivery=${r.kind}`)},g6=(e,t,n)=>{let[r=``]=t,i=YF(r);if(i===void 0)throw new R(`doctor-fix: unknown check "${r}"`);r6(n,e,{kind:`fix`,check:i})},_6=(e,t,n)=>{let[r=``,i=``]=t,a=YF(r);if(a===void 0)throw new R(`doctor-mark: unknown check "${r}"`);if(!SF.includes(i))throw new R(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${SF.join(` or `)}`);r6(n,e,{kind:`mark`,check:a,mark:i})},v6=(e,t,n)=>{let[r=``]=t,i=Object.values(n.configFor(A3(n,e)).actions).filter(e=>`slash`in e),a=i.find(e=>e.slash===r);if(a===void 0)throw new R(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(i.map(e=>e.slash))].join(`, `)||`none`})`);let o=LQ(t6(n,e).tmux);if(o.kind===`refused`)throw new R(`${r} was not typed: ${o.reason}`);n.effect({kind:`type-slash`,pane:o.hint,line:a.slash})};function y6(e,[t=``,n=``,r=``],i){let a=A3(i,e),o=i.configFor(a).actions,s=Object.hasOwn(o,t)?o[t]:void 0;if(s===void 0||!(`run`in s))throw new R(`"${t}" is not a run action this session's config declares`);let c=Gx(s);if(!i.links.signer.verify({sessionId:e,action:t,declaration:c,evaluated:n},r))throw new R(`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 l;try{l=JSON.parse(n)}catch{throw new R(`run ${t}: what the link carries is not JSON`)}let[u,...d]=l.run;if(u===void 0||u===``)throw new R(`run ${t}: the program evaluated to nothing`);let f=i.sourcesFor(a);return{sessionId:e,action:t,argv:[u,...d],envOverlay:{...b0({sessionId:e,projectDir:a.projectDir,claudeConfigDir:t6(i,e).claudeConfigDir}),...l.env},cwd:s.cwd??i.locations.homeDir,refreshes:s.refreshes.map(e=>({name:e,storage:f.get(e)}))}}const b6=new Map([[lS,h3,[1,1]],[uS,y3,[1,1]],[sS,x3,[0,1/0]],[cS,w3,[2,2]],[fS,R3,[2,2]],[pS,z3,[2,2]],[vS,K3,[0,1/0]],[mS,B3,[0,0]],[hS,U3,[0,0]],[gS,W3,[0,0]],[_S,G3,[1,1]],[yS,Y3,[2,2]],[bS,X3,[0,0]],[xS,$3,[0,0]],[SS,Z3,[0,0]],[CS,Q3,[0,0]],[dS,b3,[0,0]],[wS,e6,[0,0]],[TS,m6,[0,0]],[ES,g6,[1,1]],[DS,_6,[2,2]],[kS,v6,[1,1]],[`run`,(e,t,n)=>{let r=y6(e,t,n);n.effect({kind:`run`,id:n.runs.superseded(r),run:r})},[3,3]],[AS,(e,t,n)=>{let[r=``,i=``,a=``]=t,o=i;if(!n.links.signer.verify(BU(e,r,o),a))throw new R(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let s=zU(RU(n.stateDir),r,o);if(s.kind===`failed`)throw Error(`${r} was not ${o}: ${s.reason}`);n.journal.wrote();let{superseded:c,absent:l,unchecked:u}=s.value;n.log(`info`,`repo-config: ${r} ${o} superseded=${c.join(`,`)||`-`} absent=${l.join(`,`)||`-`} unchecked=${u.length===0?`-`:JSON.stringify(u)} (session=${e})`),n.reloadConfig(A3(n,e))},[3,3]],[jS,v3,[2,2]]].map(([e,t,n])=>[e,{handler:t,takes:n}]));new Set(b6.keys());function x6(e,t,n){let[r=``,...i]=n.split(`/`);return{verb:e,leaf:t,session:S6(r),args:Ys(()=>i.map(decodeURIComponent))}}function S6(e){let t=Ys(()=>decodeURIComponent(e));return t.ok?ZZ(t.value):{ok:!1,problem:`has ${t.problem}`}}function C6({verb:e,value:t}){let n=b6.get(e);return n===void 0?{verb:e,leaf:n}:x6(e,n,t)}function w6(e){return qS(GS(e)).map(C6)}function T6(e){return e.find(e=>e.leaf!==void 0)?.session??null}function E6(e,t){return T6(e===`dispatch`?w6(t):[C6({verb:e,value:t})])}function D6({verb:e,leaf:t,session:n,args:r},i,a){let o=[];try{if(!n.ok)throw new R(`session id ${n.problem}`);if(!i?.ok)throw new R(`its click's own session is refused, so no step of it runs`);if(i.id!==n.id)throw new R(`names session ${n.id}, not the session its click is in`);if(!r.ok)throw new R(r.problem);let[e,s]=t.takes;if(r.value.length<e||r.value.length>s)throw new R(`reads ${e===s?e:`${e} to ${s}`} after its session, and the link carries ${r.value.length}`);t.handler(n.id,r.value,{...a,effect:e=>void o.push(e)})}catch(t){throw t instanceof R&&O6.get(e)?.(a,{sid:i?.ok?i.id:`-`,args:r.ok?r.value:[],reason:t.message}),t}for(let e of o)a.effect(e)}const O6=new Map([[`run`,(e,{sid:t,args:[n],reason:r})=>e.runs.refused(t,n||`-`,r)]]);function k6(e,t,n){let r=[],i=!1;for(let a of e){if(a.leaf===void 0){r.push(`unknown effect verb "${a.verb}"`);continue}try{D6(a,t,n)}catch(e){e instanceof R||(i=!0),r.push(`${a.verb}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){t?.ok&&DZ(n.sessionState,t.id,r.join(`
|
|
497
|
+
`),n.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new R(e)}}function A6(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}function j6(e,t,n){let r=e===null?null:P3(t,e),i=t.history.begin(),a=t.navigation.begin(i.sessionState),o=[],s=e=>O$(e,e=>F3(t,e),e=>t.log(`info`,e)),c=[];try{n({...t,sessionState:s(i.sessionState),journal:i,navigating:s(a.sessionState),effect:e=>void c.push(e)})}catch(e){o.push(e)}for(let e of[a,i])try{e.commit()}catch(e){o.push(e)}if(r!==null)try{let e=r.read();c.push(...t.lanes.clicked(r.sessionId,i.written()?r.before:e,e))}catch(e){o.push(e)}t.described(c),A6(o)}function M6(e,t,n){return(r,i)=>{if(i.gone())throw new Js(e);let a=t(r),o=T6(a),s=o?.ok?o.id:null;i.journalTurns.take(e,()=>j6(s,i,e=>{try{n(a,o,e)}finally{s!==null&&i.clickLanded(s)}}))}}const N6=new Map([...[...b6].map(([e,t])=>[e,M6(e,n=>[x6(e,t,n)],(e,t,n)=>{for(let r of e)D6(r,t,n)})]),[oS,M6(oS,w6,k6)],[OS,h6]]);Object.freeze([...N6.keys()]);function P6(e){let t=N6.get(e);return t===void 0?null:{name:e,run:t}}function F6(e,t,n){n.journalTurns.take(`menu-idle`,()=>j6(e,n,n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=D$(F3(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:ea}))),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 I6=[],L6={request:({req:e,facts:t},{verbCtx:n})=>{let r=n.journalTurns.take(`request`,()=>(H6(n.sessionState,e),{effects:n.lanes.arrived(e),revision:n.sessionState.revision(e.sessionId)}));return RZ(t,{revision:String(r.revision),effects:r.effects.map(e=>GQ(e)).join(`,`)||`-`}),{answer:void 0,effects:r.effects,facts:[]}},click:({verb:e,value:t,arrival:n,gone:r},{verbCtx:i})=>{let a=[],o=null;try{e.run(t,{...i,arrival:n,gone:r,described:e=>void a.push(...e)})}catch(e){o={error:e}}return{answer:o,effects:a,facts:[]}},"menu-idle":({session:e,idle:t},{verbCtx:n})=>{let r=[];return F6(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":({of:e,done:t},n)=>{let{verbCtx:r}=n;return{answer:r.journalTurns.take(`effect-done`,()=>{let i=B6(t,n);return i.kind===`failed`&&e.session!==null&&DZ(r.sessionState,e.session,i.said,r.now()),i}),effects:I6,facts:[]}},answered:({session:e,errors:t},{verbCtx:n})=>(n.journalTurns.take(`answered`,()=>OZ(n.sessionState,e,t)),{answer:void 0,effects:I6,facts:[]})},R6=({outcome:e})=>e,z6={launch:R6,"type-slash":R6,"apply-update":R6,run:R6,"lane-setup":R6,doctor:({effect:e,outcome:t},n)=>t.kind===`failed`?t:(f6(n,e,t.gathered),Gs)};function B6(e,t){let n=z6[e.effect.kind];try{return n(e,t.verbCtx)}catch(n){return V6(e.effect,n,t.log)}}function V6(e,t,n){return t instanceof R||t instanceof qs||n(`error`,`apply: ${GQ(e)} threw: ${k(t)}`),Ks(t instanceof Error?t.message:String(t))}function H6(e,t){let{client:n,configEnv:r,...i}=t.hints,a=[{key:qQ,value:JSON.stringify(i)},{key:KQ,value:t.originRecord}];e.setBatch(t.sessionId,a.filter(({key:n,value:r})=>e.get(t.sessionId,n)!==r))}async function U6(e,t){let n=L6[e.kind],r=n(e,t),i=$6(e),a=Y6[e.kind],o=a(e,r);return o!==null&&t.log(o.level,HZ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>GQ(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?W6:o8(t,i,r.effects)}}const W6=Promise.resolve();async function G6(e,t){return await U6(e,t),t.draw(e.req,e.at,e.waitEndsAt,e.facts)}const K6={level:`info`,facts:[[`outcome`,`ok`]]},q6=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),J6={ok:`info`,failed:`warn`},Y6={request:()=>null,click:(e,{answer:t})=>t===null?K6:q6(t),"menu-idle":()=>K6,answered:()=>K6,"effect-done":({done:e},{answer:t})=>({level:J6[t.kind],facts:[[`effect`,GQ(e.effect)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},X6={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({verb:e,session:t})=>({verb:e.name,session:t}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e,answered:({session:e})=>({verb:`answered`,session:e})};function Z6(e,t,n,r){e(r instanceof qs?`info`:`error`,`apply: ${t} not applied (${n}): ${k(r)}`)}function Q6(e,t,n){return U6(e,t).then(()=>void 0,r=>Z6(t.log,e.kind,n,r))}function $6(e){let t=X6[e.kind];return t(e)}const e8={launch:({spec:e,what:t},{verbCtx:n})=>t8(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await RQ(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:Ks(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),Gs),run:({id:e,run:t},{verbCtx:n})=>n.runs.run(e,t),"lane-setup":(e,{verbCtx:t})=>t.lanes.setup(e),doctor:async(e,{verbCtx:t})=>({kind:`gathered`,gathered:await c6(t,e)})};async function t8(e,t,n){let r=await e.launch({...t,timeoutMs:u3});return r.ok?Gs:Ks(`${n} failed (${vt(r)})`)}async function n8(e,t){let n=e8[e.kind],r;try{r=await n(e,t)}catch(n){r=V6(e,n,t.log)}return{effect:e,outcome:r}}const r8={launch:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"type-slash":{key:({pane:e})=>({kind:`pane`,tmux:e}),paneWhenReached:!1},"apply-update":{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},run:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"lane-setup":{key:({sessionId:e,lane:t})=>({kind:`lane`,session:e,lane:t}),paneWhenReached:!0},doctor:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1}};function i8(e,t){return r8[e.kind].key(e,t)}function a8(e,t,n,r){let i=e=>r8[e.kind].paneWhenReached,a=[...n.filter(e=>!i(e)),...n.filter(i)],o=W6;for(let n of a){let i=o;o=e.performing(i8(n,t),async()=>{await i,await r(n)})}return o}function o8(e,t,n){return a8(e.verbCtx.journalTurns,t,n,async n=>{let r=await n8(n,e);await Q6({kind:`effect-done`,of:t,done:r},e,`${GQ(n)} ${r.outcome.kind}${`said`in r.outcome?`: ${r.outcome.said}`:``}`)})}function s8({projectDir:e,cwd:t,target:n},r){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path===void 0?null:B1(r,n.path),source:n.source})}function c8(e,t,n){let{tokens:r}=ne({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:wP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function l8(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=_r.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${_r.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function u8(e,t,n,r,i){let{report:a}=qZ(e.hookData),o=[];for(let e of a.missingRequired)o.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of a.typeMismatches)o.push(`field '${e}' expected ${t}, got ${n}`);let s=ZZ(e.hookData?.session_id);s.ok||o.push(`field 'session_id' ${s.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&o.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&o.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let c=l8(e.encoding);c.ok||o.push(c.problem);let l=Yr(e.deadline);if(l.kind===`refused`)return{ok:!1,problems:[...o,l.problem]};if(o.length>0||!s.ok||!c.ok)return{ok:!1,problems:o};for(let e of a.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let d=yr(e),{configFile:f,refusedArgs:p}=c8(e.args,e.cwd,r),m=P1(i),h=DP(f,d.configEnv),g={projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:h.source===`search`?h:{...h,path:U1(m,h.path)}};return{ok:!0,req:{...e,deadline:l,encoding:c.encoding,sessionId:s.id,hints:d,rateLimits:yne(e.hookData),requested:g,originRecord:s8(g,m),refusedArgs:p}}}function d8(e,t){switch(e){case`vars`:return{what:e,vars:f8(t)};case`segments`:return{what:e,segments:_8(t)};case`config`:return{what:e,config:x8(t)}}}function f8(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=h8(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=p8(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:m8(r.lastUpdatedMs(),t.clock)})}return o}function p8(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 m8(e,t){return e===null?null:Math.max(0,t.now()-e)}function h8(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,g8(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}`,g8(i));return t}function g8(e){return e.kind}function _8(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=y8(n),o=v8(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:b8(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function v8(e){let t=new Map;for(let n of Mx(e.presets))for(let r of Zv(Fx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=qv(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function y8(e){let t=[],n=new Set;for(let r of Zv(Sx(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 b8(e,t,n){let r=new Set([...bC(e,t).keys()].flatMap(e=>LC(e,n)));return Array.from(r).sort()}function x8(e){return e===null?null:e.config}const S8=[`vars`,`segments`,`config`];function C8(e){return typeof e==`string`&&S8.includes(e)}const w8=e=>({resp:e,exitAfterFlush:null,delivered:lQ}),T8=e=>({kind:`reply`,...e}),E8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},D8=(e,t)=>T8(w8({ok:!1,error:t,code:e,daemonV:3}));function O8(e){let t=ZZ(e.sessionId);if(!t.ok)return D8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return D8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${mb.join(`, `)}): it predates the lane toggles — update it`);let n=Sb(e.lane);return n===null?D8(`BAD_REQUEST`,`subscribe needs a lane, one of ${mb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}function k8(e){let{session:t,path:n,seconds:r}=e,i=ZZ(t);if(!i.ok)return{ok:!1,problem:`record's session ${i.problem}`};if(typeof n!=`string`||!u(n))return{ok:!1,problem:`record's path is not an absolute path: ${JSON.stringify(n)}`};let a=Nr(r);return a.ok?{ok:!0,session:i.id,path:n,seconds:a.seconds}:{ok:!1,problem:`record's seconds ${JSON.stringify(r)} ${a.problem}`}}function A8(e,t){let n=k8(t);if(!n.ok)return D8(`BAD_REQUEST`,n.problem);let{session:r,path:i,seconds:a}=n;return{kind:`held`,start:t=>cQ(e.recorder,e.clock,r,i,a,t).then(e=>w8({ok:!0,recorded:e}),e=>w8({ok:!1,error:e instanceof Error?e.message:String(e),code:e instanceof sQ?`RENDER_FAILED`:`BAD_REQUEST`,daemonV:3}))}}function j8(e,t){return e.v===3?null:(e.v>3?t(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):t(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:lQ})}async function M8(e,t,n,r,i){if(t.kind===`url`)return T8(w8(await B8(e,t.frame,n,r,i)));let a=t.req;if(!a||typeof a!=`object`||typeof a.v!=`number`)return D8(`BAD_REQUEST`,`malformed request`);let o=j8(a,e.log);return o===null?a.kind===`subscribe`?O8(a):a.kind===`record`?A8(e,a):typeof a.kind!=`string`||!Object.hasOwn(E8,a.kind)?D8(`BAD_REQUEST`,`unknown kind`):T8(await N8(e,a,n,r,i)):o}async function N8(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,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:w}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:lQ};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return w8(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 w8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:P8(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:yo(),renderCache:c.stats,effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:e.sessionState.size(),observers:e.sessionState.observers(),revision:e.sessionState.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),linkIds:e.linkIds.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(st(new Date(o.now()))),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:t4(w)})});if(t.kind===`render`){let c=new Date(o.now()),l=st(c),u=o.monotonic(),d=et(r,u),f=[],p=++a.requestsTotal,m=u8(t,a,e.log,e.home,e.storedRoot),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:Ao(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:bne(t.hookData),frame:n},l,p);m.ok&&(RZ(f,{sid:m.req.sessionId}),h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await G6({kind:`request`,req:m.req,at:l,waitEndsAt:$e(u,Xr(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({resp:t,motion:n,answersClick:r,pipeShown:i,delivered:a})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r.length>0&&Q6({kind:`answered`,session:m.req.sessionId,errors:r},e,`sid=${m.req.sessionId}`),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:U8(e),resp:uQ(e),delivered:lQ})):X8(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,RZ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:_,line:v}=VZ(`render`,f,g.outcome,tt(o,u));return e.log(_,v),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return w8(await R8(e,r,n,i,(n,r)=>z8(e,t,n,r)));if(t.kind===`debug`){if(!C8(t.what))return w8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${S8.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`?L8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??$b(`colorCompatibility`)):I8};return w8({ok:!0,debug:d8(t.what,n)})}throw Error(`no reply for request ${k(t)}`)}function P8(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 F8={endcaps:$b(`endcaps`),colorCompatibility:$b(`colorCompatibility`),wrap:$b(`autoWrap`),padding:$b(`padding`),width:1/0},I8=new Map;function L8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,hne(i,{...F8,colorCompatibility:t}));return n}async function R8(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${et(t,o)}ms`]],c=await i(s,()=>n()||r());RZ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=VZ(`click`,s,c,tt(a,o));return e.log(l,u),J8(c)}async function z8(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};RZ(n,{via:`cli`});let{url:a}=t;return typeof a==`string`?V8(()=>K8(e,a,i,n,r)):{kind:`bad-request`,problems:[`a click's link is a string, got ${typeof a}`]}}async function B8(e,t,n,r,i){return R8(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(RZ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Ar.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${k(i)} is not one this daemon speaks (${[...Ar].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return V8(()=>K8(e,a,o,n,r))})}async function V8(e){try{return await e()}catch(e){return H8(e)}}function H8(e){return e instanceof R?{kind:`bad-request`,problems:[e.message]}:e instanceof Js?{kind:`abandoned`,error:e}:U8(e)}function U8(e){return e instanceof qs?{kind:`closing`,error:e}:{kind:`threw`,error:e}}const W8={link:`to`,"tmux-status":`linkTo`},G8={link:`verb`,"tmux-status":`linkVerb`};async function K8(e,t,n,r,i){let a=XS(t);if(!a.ok)return{kind:`bad-request`,problems:[a.problem]};RZ(r,{[W8[n.via]]:a.to});let o=e.links.to;return a.to===o?q8(e,a.verb,a.value,n,r,i):{kind:`bad-request`,problems:[`the link is addressed to renderer ${JSON.stringify(a.to)}, and this is ${JSON.stringify(o)}`]}}async function q8(e,t,n,r,i,a){if(t===`range`)return r.via===`tmux-status`?{kind:`bad-request`,problems:[`a status-line link names another status-line click`]}:(RZ(i,{verb:t}),Y8(e,n,i,a));let o=P6(t);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};RZ(i,{[G8[r.via]]:t});let s=E6(t,n),c=s?.ok?s.id:null;RZ(i,{sid:c??`-`});let{answer:l}=await U6({kind:`click`,verb:o,value:n,arrival:r,session:c,gone:a},e);if(l!==null)throw l.error;return{kind:`ok`}}function J8(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 uQ(e.error)}}async function Y8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);return s.kind===`refused`?o(s.reason):(RZ(r,{link:s.url}),$i(s.url)?K8(e,s.url,{via:`tmux-status`},r,i):(await f3(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,u3,e.tmp),{kind:`ok`}))}const X8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:lQ});function Z8(e,t){let n=ce(`sha256`).update(t).digest(`hex`).slice(0,16);return s.join(e,`update-act`,n)}const Q8={kind:`idle`};function $8(e){if(e===null)return Q8;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 e5=e=>({stdout:s.join(e,`stdout`),stderr:s.join(e,`stderr`),status:s.join(e,`status`)}),t5=e=>s.join(e,`record.json`);function n5(e){let t;try{t=h.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 r5(e){let t=Do(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 i5(e,t){let n=s.join(e,`.removed-${t}-${process.pid}`);try{h.renameSync(s.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}h.rmSync(n,{recursive:!0,force:!0})}const rre=e=>e.now()-o.uptime()*1e3;async function ire(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 are(e){try{return JSON.parse(h.readFileSync(t5(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const ore=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function sre(e,t,n,r){let i=null;async function a(a){let o=s.join(e,String(a)),c=are(o);if(c===null)return null;if((i===null||!ore(i.record,c))&&(i={record:c,ours:await ire(c,t,n,rre(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=e5(o),u=Yt(l.status),d=u===null?null:r5(l.stderr)??r5(l.stdout);if(!h.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=n5(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${s.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function cre(e,t,n){h.mkdirSync(e,{recursive:!0});let r=h.mkdtempSync(s.join(e,`.claim-`));try{return h.writeFileSync(t5(r),JSON.stringify(n)),h.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{h.rmSync(r,{recursive:!0,force:!0})}}async function lre(e,t,n,r,i,a,o,c){let l=(n??0)+1,u=s.join(t,String(l)),d=e.launchJobSync(i,e5(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!cre(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return a5;if(n5(t).some(e=>e>l))return i5(t,l),a5;f=!0}finally{f?d.release():d.withdraw()}for(let e of n5(t).filter(e=>e<l))i5(t,e);return{ok:!0,act:l}}const a5={ok:!1,reason:`another act claimed this bundle first`};function ure(e,t,n){let r=e5(s.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}var o5=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 s5(e){return e.kind===`source`?e.newer.digest:Ko(e.newer)}const c5=e=>`${e.version} [${Cn(e.digest)}]`;function l5(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:c5(e.newer),running:c5(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Ko(e.newer),running:Ko(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Jo}@${Ko(e.newer)}`,`install`]}}}}function dre(e,t,n){if(e===null)return[];let r=s5(e);if(!n.enabled||n.dismissed===r)return[];let i=l5(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(`
|
|
498
|
+
`),c=t.kind===`running`?mU(`[${i.busy}]`,null):mU(`[${i.act}]`,HS(n.to,[{verb:wS,args:[n.sessionId]}])),l=[mU(a,null),c,mU(`[dismiss]`,HS(n.to,[{verb:sS,args:[n.sessionId,Az,r]}])),mU(`[disable]`,HS(n.to,[{verb:fS,args:[n.sessionId,jz,`false`]},{verb:sS,args:[n.sessionId,Mz,`false`]}]))],u=o.map(e=>[mU(e,null)]);return[{severity:dU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function fre(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return pre(t)}}function pre(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}function mre(e){switch(e.kind){case`current`:return[`info`,`build: current ${c5(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${c5(e.source)}, running ${c5(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function hre(e){switch(e.kind){case`current`:return[`info`,`release: current ${Ko(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Ko(e.latest)}, running ${Ko(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Ko(e.installed)}, latest ${Ko(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function gre(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=so(`unread`),g=so(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new qs(`apply-update`);return t},v=sre(s,_,r,n),y=null,b=null,x=Fe(m),S=Fe(m),C=new o5,w=e=>C.run(`acts`,e),T=!1,E=[],ee=(e,t)=>{E.push(n.every(t,e,{unref:!0}))},D=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function te(){let e=D(),t=e===null?null:s5(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(Az,[t])})}function O(){let e=T?I:fre(h,g),r=UZ(t.get(),e,ut(n));(0,X.runInAction)(()=>t.set(r)),te()}function k(){let e=On(a,()=>N(o));return h=F(e),x(mre(e)),O(),e}async function ne(){let e=Xo(wn,await Yo(Jo,d,u,n));g=F(e),S(hre(e)),O()}let A=null,re=Fe(m);async function ie(e){try{let t=await e();return A=null,{ok:!0,value:t}}catch(e){return e instanceof qs?{ok:!1,error:e.message}:(A=`update act files (${s}): ${e.message}`,re([`error`,A]),{ok:!1,error:A})}}function ae(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=ure(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 oe(){let e=await ie(async()=>{let e=await v.read();return T||ae(e),e});if(T||!e.ok)return;let t=$8(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`),k(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let se;async function ce(){await w(oe),!T&&(se=n.after(2e3,()=>void ce(),{unref:!0}))}return{arm(){let e=k();ee(k,c),E.push(()=>se?.()),ce(),e.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),l))},close(){T=!0,O(),E.forEach(e=>e())},notice:e=>dre(D(),y??Q8,e),running:()=>w(async()=>{let e=await ie(()=>v.read());return e.ok&&$8(e.value).kind===`running`}),error:()=>A,act:()=>w(async()=>{if(T)throw new qs(`apply-update`);let e=await ie(()=>v.read());if(T)throw new qs(`apply-update`);if(!e.ok)throw new R(`apply-update: ${e.error}`);let t=D();if(t===null)throw new R(`apply-update: nothing newer is known to apply`);let i=l5(t),a=e.value;if($8(a).kind===`running`)throw new R(`apply-update: already ${i.busy}`);let o=await lre(r,s,a===null?null:a.act,s5(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new R(`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 _re(){return X.observable.box(so(`unread`),{deep:!1})}function u5(e,t){try{return F(t.statSync(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function vre(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function yre(e){let{targets:t,intervalMs:n,filesystem:r,held:i,exit:a,log:o,clock:s}=e,c=Fe(o),l=t.map(e=>({path:e,stamp:u5(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=u5(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!vre(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 bre=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 d5=`pass`,f5={okMs:5*6e4,failedMs:45e3},xre=f5.okMs;function p5({failures:e}){return Mte(f5,e,xre)}function Sre(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function Cre(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function wre(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function Tre(e,t,n,r){let i=[{path:n,filenames:[`HEAD`,`index`]},{path:s.join(r,`refs`,`heads`),recursive:!0}],a=i.map(t=>xc(e,t.path));return{key:`git:${t}:${i.map((e,t)=>`${e.path}@${Sc(a[t])}`).join(`|`)}`,targets:{dirs:i},unbound:a.some(e=>typeof e==`string`||`unreadable`in e)}}function Ere(e){return e.find(e=>e.kind===`ok`)?.value.branch}function m5(e){e.missed=!0,Rj(e,`unread`)}function Dre(e,t){return e.missed&&e.reading.get().kind===`pending`&&Lj(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function Ore(e,t){let n=Vj(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:Vj(t)})}const kre=L(`git cache closed`,`read`);function h5(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Are=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 lo(e.maxPrLookups??2),this.logger=e.logger??Ie;let t=e.ledger??new Qj(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 Mj({filesystem:Pn,clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`settled`)return Gj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>Ore(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:kre};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 bre,watch:this.followWatch(e,null).watch,period:new Pj(()=>{n.refresh.share(d5,()=>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=Tre(this.watchers.filesystem,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(d5,()=>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&&m5(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(d5,()=>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:Fj(),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=wre(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(Cre(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(h5(`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,Lj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of YU(n.value))c.add(e)});let l=Ere(o),u=a===null||i.length===0?`-`:l===void 0?Dre(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}`,Sre(n),c.size===0?F(null):L([...c].join(`; `),`read`),tt(this.clock,t))}prSource(e){let t={period:new Pj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:Fj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(h5(`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?(m5(t),`owed`):(Rj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Lj(t,a.outcome),t.period.landed(p5(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(h5(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(r)}`,n,i,tt(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||(Lj(t,i),t.period.landed(p5(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())zj(n,t);e.pr!==null&&zj(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()}};const g5={"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}},_5=new n(`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`);function jre(e){let t=null;return{table:()=>e.closing.aborted?Promise.resolve(g5):t??=Mre(e).catch(t=>(e.log(`error`,`pricing load threw: ${String(t)}`),g5))}}const v5=e=>s.join(e,`usage`,`pricing.json`);async function Mre(e){let t=await Nre(e);if(t!==null)return t;let n=e.closing.aborted?null:await Fre(e.closing);return n===null?(Pe(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(g5).length} models`),g5):(e.closing.aborted||await Pre(e,n),n)}async function Nre(e){try{let t=JSON.parse(await h.promises.readFile(v5(e.cacheRoot),`utf8`));return typeof t.timestamp==`number`&&t.timestamp>=e.clock.now()-864e5&&y5(t.data)?t.data:null}catch(t){return t.code!==`ENOENT`&&e.log(`warn`,`pricing disk cache unreadable: ${String(t)}`),null}}async function Pre(e,t){let n=v5(e.cacheRoot),r=`${n}.${process.pid}.${de()}`;try{await h.promises.mkdir(s.dirname(n),{recursive:!0}),await h.promises.writeFile(r,JSON.stringify({data:t,timestamp:e.clock.now()}),`utf8`),await h.promises.rename(r,n)}catch(t){e.log(`warn`,`pricing disk cache not written: ${String(t)}`),await h.promises.rm(r,{force:!0}).catch(()=>{})}}function Fre(e){return new Promise(t=>{let n=ve({hostname:_5.hostname,path:_5.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3,agent:!1,signal:e},e=>{if(e.statusCode!==200){Pe(`HTTP ${e.statusCode}: ${e.statusMessage}`),e.resume(),t(null);return}let r=``,i=0;e.setEncoding(`utf8`),e.on(`data`,e=>{if(i+=Buffer.byteLength(e),i>1048576){Pe(`Response too large`),n.destroy(),t(null);return}r+=e}),e.on(`end`,()=>{try{let e=JSON.parse(r),n=e._meta,i={};for(let[t,n]of Object.entries(e))t!==`_meta`&&(i[t]=n);y5(i)?(Pe(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),Pe(`Pricing last updated: ${n?.updated||`unknown`}`),t(i)):(Pe(`Invalid pricing data structure`),t(null))}catch(e){Pe(`Failed to parse JSON:`,e),t(null)}}),e.on(`error`,e=>{Pe(`Response error:`,e),t(null)})});n.on(`error`,e=>{Pe(`Request error:`,e),t(null)}),n.on(`timeout`,()=>{Pe(`Request timeout`),n.destroy(),t(null)}),n.end()})}function y5(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`||typeof e.cache_write_5m!=`number`)return!1}return!0}function Ire(e,t){let n=t[e];if(n)return n;let r=e.toLowerCase();for(let[e,n]of Object.entries(t))if(e.toLowerCase()===r)return n;for(let{pattern:e,fallback:n}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=>r.includes(e))&&t[n])return t[n];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}}function Lre(e,t){let n=t.message?.usage;if(!n)return 0;let r=Ire(Rre(t),e),i=n.input_tokens||0,a=n.output_tokens||0,o=n.cache_creation_input_tokens||0,s=n.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}function Rre(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`}var b5=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 zre(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 Bre={okMs:60*1e3,failedMs:10*1e3},x5={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function S5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function C5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const Vre={entries:0,cost:0,breakdown:C5(),days:new Map};async function Hre(e,t,n,r){let i=$K(new Date(S5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=null,l=new Map;for(let[t,n]of e.days)t>=i&&l.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let r=e.costUSD??Lre(c??=await n.table(),e.raw);o+=r,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=$K(new Date(e.timestamp));if(u<i)continue;let d=l.get(u)??{...ZK};d.cost+=r,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,l.set(u,d)}return{entries:a,cost:o,breakdown:s,days:l}}function Ure(e){let t=0,n=0,r=C5(),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)??{...ZK};QK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:x5,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 w5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function Wre(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!w5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...ZK};QK(r,t),n.set(e,r)}return Object.fromEntries(n)}async function Gre(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 T5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function E5(e,t){(0,X.runInAction)(()=>e.set(t))}var Kre=class{sessions=X.observable.map(void 0,{deep:!1});flight=new b5;scans;daySets=new Map;speedFlight=new b5;requestFlight=new b5;staleAgeMs;host;pricing;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.pricing=e.pricing,this.clock=e.clock,this.log=e.logger??Ie,this.ledger=e.ledger??new Qj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new qj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??Bre,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=fo(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:F(T5(t.kind===`ok`?t.value.sessionInfo:x5,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 so(`unread`);let r=n.failure.get();return r===null?F(T5(n.record?.sessionInfo??x5,t)):L(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,tt(this.clock,i)),E5(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 Gj(L(`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`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||w5(i.transcriptPath,t)?I:F(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return E5(this.hold(e).speed,t),t;let r=zre(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=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return E5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??so(`unread`):I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,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),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],failure:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+p),i={roots:r,sums:new $C(`today over ${e.join(`,`)}`,()=>Wre(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await J0(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of r2(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 i2(e,r,Vre,(e,t)=>Hre(e,t,this.pricing,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 r2(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...Ure(i),mainStamp:a})}async scan(e){try{let t=S5(this.clock.now()),n=await K0(e),r=[];for(let e of n){let n=await q0(go(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await q0(_o(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:po(a)})}}let i=[],a={hits:0,misses:0};return await Gre(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?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=$K(new Date(e)),n=0,r=0,i=0;return(0,X.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},D5=class{values=X.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,X.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},O5=class{sessions;flight=new b5;constructor(e,t,n,r,i=Ie,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new D5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=fo(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})}return this.flight.run(e,()=>this.fold(e,t,r))}async fold(e,t,n){let r=this.clock.monotonic(),i=await i2(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(e)}`,`request`,i,tt(this.clock,r)),i.kind===`failed`)return this.store(e,n,i);if(i.kind===`absent`)return this.store(e,n,{kind:`ok`,value:n?.value??this.empty});let{folded:a,longLines:o}=i.value;for(let e of r2(o))this.log(`info`,e);return this.store(e,a,{kind:`ok`,value:a.value})}answer(e){return this.sessions.get(e)?.answer??so(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function qre(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 Jre=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(void 0,qre,(e.ledger??new Qj(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 Pe(`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);Pe(`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?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,k5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,k5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(Pe(`No main chain entries with usage data found`),I):(Pe(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function k5(e){return e.context_window?.context_window_size??2e5}const Yre={messageCount:0,nonPrompts:0,recent:[]},Xre=new Set([`turn`,`interrupt`,`claude-code`]);function Zre(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!Xre.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function Qre(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 $re=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(Yre,Zre,(e.ledger??new Qj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){Pe(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?A5(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:A5(e,n,r)}};function A5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`,n.failedAt):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:Qre(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 eie={command:null,todos:[],pending:[],done:[]};function j5(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 tie(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 nie(e,t){if(t.isSidechain)return e;let n=tie(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=j5(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 rie(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>j5(e,t.name),[]),done:e.done}}var iie=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new O5(eie,nie,(e.ledger??new Qj(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`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(rie(t.value))}const N5=3e4;var aie=class{names;constructor(e){let t=e.logger??Ie;this.names=new qj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>oie(e.launcher,t),every:()=>({okMs:N5,failedMs:N5}),watch:Kj,maxEntries:64,logger:t,ledger:e.ledger??new Qj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function oie(e,t){let n=await Ws(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const P5=6e4,sie={okMs:P5,failedMs:P5};function cie(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function F5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var lie=class{name;user;constructor(e){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>sie,watch:Kj,maxEntries:1,logger:t,ledger:e.ledger??new Qj(t),clock:e.clock};this.name=new qj({...n,name:`host.name`,read:()=>F5(`name`,()=>cie(o.hostname()))}),this.user=new qj({...n,name:`host.user`,read:()=>F5(`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()}},uie=class{known=new D5(64);refreshes;constructor(e,t=Ie,n=new Qj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=die(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=kI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,tt(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??so(`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 die(e){try{let t=h.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:po(t)}catch(e){return`unread:${e.code??`error`}`}}const fie=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function pie(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 mie=class{known=new D5(256);refreshes;constructor(e,t=Ie,n=new Qj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=fo(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??so(`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 hie(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,tt(this.clock,r)),i}};async function hie(e){let t=await gie(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function gie(e){for(let t of[65536,1048576]){let n=await Eo(e,t);if(n.kind!==`ok`)return n;let r=_ie(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function _ie(e,t){let n=e.toString(`utf8`).split(`
|
|
499
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!fie.test(t))continue;let r=pie(t);if(r!=null)return r}return null}const I5=e=>rH(e),L5=e=>s.join(e.storage.folder,I5(e.sessionId)),R5=e=>JSON.stringify([e.folder,e.generation]),z5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var vie=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new qj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(L5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Kj,maxEntries:256,logger:e.logger,ledger:e.ledger??new Qj(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{this.watchers.filesystem.mkdirSync(e),n=vc(this.watchers.filesystem,e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!yc(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(R5(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?vc(this.watchers.filesystem,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:${R5(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(R5(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=R5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>z5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(s.join(n.folder,s.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(L5(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=vc(this.watchers.filesystem,r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&yc(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=>z5(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=>z5(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(R5(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=Ac(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=L5(e),r;try{r=await this.watchers.filesystem.readFile(n)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=iM(r);return i.kind===`failed`?L(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${z(e.folder)} scanned=${r} removed=${i} took=${tt(this.clock,t)}ms`;try{let t=await this.watchers.filesystem.readdir(e.folder);for(let a of t){if(a.kind!==`file`||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await this.watchers.filesystem.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&I5(t.sessionId)===a.name);if(r>=n||o)continue;await this.watchers.filesystem.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 yie(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new lie({clock:n,logger:r,ledger:i}),gitProvider:new Are({inner:new CW(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new Kre({host:e.host,pricing:e.pricing,clock:n,logger:r,ledger:i}),contextProvider:new Jre({clock:n,logger:r,ledger:i}),metricsProvider:new $re({clock:n,logger:r,ledger:i}),activityProvider:new iie({clock:n,logger:r,ledger:i}),tmuxService:new aie({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new uie(n,r,i),cacheExpiry:new mie(n,r,i),managedStorage:new vie({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new iq,log:e.logger,clock:n}}function*B5(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*bie(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 Mx(e.presets)){for(let n of Zv(Fx(e,t).node))n.when!==void 0&&(yield n.when);let n=Lx(e,t);for(let e of dv){let t=n[e];fv(t)&&(yield t)}}for(let[,t]of B5(e))for(let[,e]of oy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Kx(t))yield e}function xie(e,t,n){let r=CG(t),i=new Set,a=new Set,o=new Set;for(let e of bie(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of wC(e,t.helpers))a.add(n);for(let n of jC(e,t.helpers))o.add(n)}for(let[,e]of B5(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 Mx(t.presets))for(let n of Zv(Fx(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=>!eS(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(B5(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 Sie(e){return Math.floor(Math.max(e/4,e*xi-67108864))}const Cie={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function V5(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[nH(eC(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[eC(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>tC(e)(t)&&t!==nH(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${kP(e,`<default>`)}: projections=${[...DG(n).keys()].join(`,`)||`-`} instantSegments=${sZ(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 wie=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Tie=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${wie(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Eie(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.projectDir)} cwd=${z(e.cwd)} cause=${z(Tie(t))} state=${n} files=${z(kP(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 Die(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function Oie(e,t,n){return e+`\0`+t+`\0`+(n??``)}function kie(e,t){return new Set(Mx(e.presets).filter(n=>Fx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Aie(e,t,n){let{loaded:r,dropped:i,unreached:a}=t.state.plugins,o=[...new Set([...t.state.plugins.roots,s.join(t.projectDir,IH)])];return Tj(e,{named:[...XH(n,t.projectDir,t.cwd,t.configFile),...o,...r.map(e=>e.path),...[...i,...a].map(e=>e.path),...new Set([...t.state.sources.values()].map(e=>e.folder))],whole:o})}function jie(e){return e.filter(Boolean).join(`
|
|
500
|
+
`)||null}const H5=e=>e instanceof Error?e.message:String(e);function U5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Mie(e){let{loaded:t,chain:n}=e;return Uv({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:U5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...U5(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 Nie(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 W5(e,t,n){let r=[];try{let i=SK(t.locs,t.layers,JK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Nie(i.config,n)};return{kind:`resolved`,...a,key:Mie(a),warnings:r}}catch(e){return e instanceof Cy&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function G5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??JK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new lw(t.clock),m=new OM(gM,p,o.globals.default_empty_value??``,t.sessionState),h;try{h=tZ(o,m,n,t.compile??eZ(t.links),Fie),f.push(...h.loadWarnings);let r=m.view(hM);f.push(...iZ(o,r,n,Y5)),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 Cy&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:kie(l,u),fileHeldSettings:h$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>xie(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 K5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:tt(i,e.started)},o=t=>jie([...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:H5(r.cause),cause:r.cause}}}function Pie(e,t,n,r,i=null){let a=W5(t,n,r.storage);if(a.kind===`failed`)return K5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:G5(a,r);return K5(e,n,a.warnings,o,r.clock)}function q5(e,t,n,r,i=null){let a=r.clock.monotonic(),o=eU(r.locations,RU(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 Pie({repos:s,advisories:[sU(r.locations,e,t),aU(o),qH(s)],started:a},t,c,r,i)}function J5(e,t,n){let r=W5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:G5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${H5(i.cause)}`,{cause:i.cause});return i.state}const Fie=new Set([`directory`]),Y5=new Set([`view`]);function Iie(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c={sources:e.sources},l=r.follow(n,c),u=e.registry.view(l.runs),d=X.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,X.runInAction)(()=>{l.follow(e,c),d.set({facts:e})})},p=[],m=()=>(0,X.runInAction)(()=>{for(let e of p)e();let e=u.dispose();return l.dispose(),e});try{iZ(e.config,u,t,Y5)}catch(e){throw m(),e}let h;try{h=i({sessionId:s,state:e,store:u.variableStore,declared:()=>d.get(),followed:l,onDispose:e=>p.push(e)})}catch(e){throw m(),e}OX(e.compiled,u.variableStore,u,h);let g=(0,X.reaction)(()=>[h.payload(),h.selections(),u.published()],()=>a(s),{equals:X.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:u.variableStore,registry:u,source:h,requested:f,facts:()=>d.get().facts,settle:e=>l.settle(e),followed:{stamped:l.stamped,failure:l.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var Lie=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??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},e.watchers.filesystem.mkdirSync(IU(e.stateDir));let{dir:n,name:r}=Cj(e.watchers.filesystem,LU(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)??oZ(t,this.deps.links)}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=Oie(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`,V5(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??J5(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=${P(this.accountedBytes())}/${P(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.placeView(i,a),a.requested(n),a;this.placeView(i,void 0);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=Iie(t,e.cwd,n,{facts:this.deps.facts,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.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.placeView(a,o),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}placeView(e,t){let n=this.views.get(e);this.views.delete(e),t!==void 0&&this.views.set(e,t),t!==n&&this.observers.onSessionViewMoved?.(e)}sessionView(e){return this.views.get(e)??null}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.placeView(e.sessionId,void 0),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 q5(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=${P(this.accountedBytes())}/${P(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`,Die(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`,V5(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=Aie(this.deps.watchers.filesystem,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 Rie=e=>!K1(e)&&!_I(e)&&e!==`update.dismissed`&&e!==iS;var zie=class{past=X.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:j1(e,Rie,(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 R(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,X.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const X5=(e,t)=>e.kind===`ok`?F(t(e.value)):e;function Bie(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest??so(`unread`)}}const Z5=(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 Vie({pullRequest:e,...t}){return t}function Q5(e,t,n,r,i){let{lanes:a}=n,o=a.git,s=(e,t)=>UZ(e,t,i),c=e?.builtins,l={session:s(c?.session,a.usage),today:s(c?.today,n.today),speed:s(c?.speed,a.speed),context:s(c?.context,a.context),metrics:s(c?.metrics,a.metrics),activity:s(c?.activity,a.activity),cache:s(c?.cache,a.cache),autocompact:s(c?.autocompact,a.autoCompact),git:s(c?.git,X5(o,Vie)),pr:s(c?.pr,Bie(o)),tmux:s(c?.tmux,X5(a.tmuxSession,e=>({session:e}))),hostName:s(c?.hostName,a.hostName),hostUser:s(c?.hostUser,a.hostUser)},u=Object.fromEntries([...a.sources].map(([t,n])=>[t,s(e?.sources[t],n)])),d=Object.fromEntries([...n.runs].map(([t,{reading:n,fault:r}])=>{let i=e?.runs[t],a=s(i?.reading,n);return[t,i!==void 0&&i.reading===a&&i.fault===r?i:{reading:a,fault:r}]})),f={builtins:l,sources:u,runs:d,update:r,diagnostics:n.faults};return e!==void 0&&Z5(l,e.builtins)&&Z5(u,e.sources)&&Z5(d,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:2,session:t,seq:e===void 0?1:e.seq+1,...f}}function Hie(e,t,n){let r=aM(e),i=(0,X.computed)(()=>t().runs[r]),a=(0,X.computed)(()=>{let e=i.get();return e===void 0?n(r):Eq(e.reading)},{equals:X.compareStructural});return{digest:r,current:()=>a.get(),fault:()=>i.get()?.fault??null}}function Uie(e,t,n,r){if(t.kind===`failed`)return io(e,t.reason);try{let i=Q5(e.line.facts,r,t.readings,t.update,n),a=i===e.line.facts?e.line:{at:n,facts:i};return a===e.line&&e.failure===null?e:{line:a,failure:null}}catch(t){return io(e,`stamping the facts document: ${String(t)}`)}}function Wie({providers:e,update:t,runs:n}){let{clock:r,log:i}=e;return{follow(a,o){let s=a.sessionId,c=new Sj,l=X.observable.map(void 0,{deep:!1}),u=!1,d=(e,t)=>{if(!l.has(t))return L(`the run of ${sM(e.read)} is not declared by this view`,`read`);let{failure:n}=y.get();return n===null?so(`unread`):L(`the run of ${sM(e.read)} is in no document: ${n}`,`read`)},f=JSON.stringify(s),p=(t,{sources:n})=>{try{let{result:{lanes:r,faults:a},acquired:o,released:s}=c.declare(()=>xq(e,c,t,n));for(let e of a)i(`error`,`session view declaration threw sid=${f} ${e}`);return o+s>0&&i(`info`,`session view declared sid=${f} acquired=${o} released=${s} held=${c.size}`),r}catch(e){return i(`error`,`session view declaration threw sid=${f}: ${k(e)}`),vq(L(`view declaration threw: ${String(e)}`,`read`),[...n.keys()])}},m=X.observable.box({facts:a,lanes:p(a,o)},{deep:!1}),h=(0,X.computed)(()=>{let{facts:t}=m.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>m.get().lanes}}}),g=(0,X.computed)(()=>Sq(h.get())),_=(0,X.computed)(()=>new Map([...l].map(([e,{run:t}])=>[e,{reading:t.current(),fault:t.fault()}]))),v=(0,X.computed)(()=>({...g.get(),runs:_.get()})),y,b=(0,X.reaction)(()=>{try{return{kind:`read`,readings:v.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,X.runInAction)(()=>{let t=y.get(),n=Uie(t,e,ut(r),s);n.failure!==null&&n!==t&&i(`error`,`session facts sid=${f}: ${n.failure}`),y.set(n)}),{onError:e=>i(`error`,`session facts threw sid=${f}: ${k(e)}`)});try{let e=ut(r);y=X.observable.box({line:{at:e,facts:Q5(void 0,s,v.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw b(),c.close(),e}return{runs:{declare:(e,t)=>{if(u)throw Error(`the run of ${sM(t.read)} was declared after its view's follow was disposed`);let r=aM(t);return e.take(`facts.run:${r}`,()=>{let e=new Sj,i=n.declare(e,t),a=Hie(t,()=>y.get().line.facts,e=>d(t,e));return(0,X.runInAction)(()=>l.set(r,{run:i,held:e,lane:a})),()=>{(0,X.runInAction)(()=>l.delete(r)),e.close()}}),l.get(r).lane}},stamped:()=>y.get().line,failure:()=>y.get().failure,follow:(e,t)=>{let n=p(e,t);(0,X.runInAction)(()=>m.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:Pq(h.get(),e,t)}},dispose:()=>{u=!0,b();for(let{held:e}of l.values())e.close();c.close()}}}}}function $5(e,t){return e===t||e?.cause===t?.cause&&e?.reason===t?.reason}function Gie(e,t,n){if(t.kind===`failed`){let n={cause:`inputs`,reason:t.reason};return $5(e.failure,n)?e:{...e,failure:n}}let r=t.facts===null?null:{cause:`facts`,reason:t.facts};return $5(e.failure,r)&&t.stamped===e.stamped&&t.request===e.request&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,request:t.request,picks:n(),compose:t.compose,draw:t.draw,failure:r}}function Kie(e){return({sessionId:t,state:n,store:r,declared:i,followed:a,onDispose:o})=>{let s=n=>e.sessionState.get(t,n),c=r.derive(`session.effective`,`computed`,()=>qq(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),u=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...g$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),d=()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t)}),f=a.failure(),p=X.observable.box({stamped:a.stamped(),request:i().facts,picks:d(),compose:l.read(),draw:u.read(),failure:f===null?null:{cause:`facts`,reason:f}},{deep:!1});o((0,X.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),request:i().facts,compose:l.read(),draw:u.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,X.runInAction)(()=>{let r=p.get(),i=Gie(r,n,d);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${n.reason}`),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{stamped:e,compose:t,draw:n}=p.get();return Dq(e.facts,t,n)});return{payload:()=>m.read(),effective:()=>p.get().draw.effective,facts:()=>p.get().stamped.facts,turn:()=>{let{stamped:e,request:t,picks:n,draw:r}=p.get();return{document:e,request:t,state:{...n,history:r.history,back:r.back}}},held:()=>p.get().failure?.cause===`inputs`,home:()=>p.get().compose.home,hints:()=>p.get().compose.hints,failure:()=>p.get().failure,selections:()=>p.get().draw.effective,state:()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t),history:p.get().draw.history,back:p.get().draw.back})}}}const qie=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function e7(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?qie[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const Jie={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 Yie({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=e7(t),o=e7(n),s={};for(let e of r){let t=Jie[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 Xie(e){return{ok:!0,band:e.rows.map(e=>XP(e).map(Yie))}}function Zie(e){return KP(Xie,e)}const Qie=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function t7(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:Qie[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 $ie={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 eae(e){return e.replaceAll(`#`,`##`)}function tae({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=$ie[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${t7(e)}`,`bg=${t7(t)}`,...r].join(`,`)}]`}function nae(e,t){let n={},r=e=>{let r=tae(e)+eae(e.text);if(e.link===void 0)return r;let i=t(e.link);return i===null?r:(n[i]=e.link,`#[range=user|${i}]${r}#[norange]`)};return{rows:e.rows.map(e=>XP(e).map(r).join(``)),links:n}}function rae(e,t){return t.frame(t=>KP(e=>nae(e,t),e))}var iae=class{ranges=new Map;constructor(e,t=256){this.source=e,this.cap=t}frame(e){let t=new Set,n=e(e=>(t.add(e),this.rangeOf(e)));for(let e of this.ranges.keys()){if(this.ranges.size<=this.cap||t.has(e))break;this.ranges.delete(e),this.source.evicted()}return n}rangeOf(e){let t=this.ranges.get(e);if(t!==void 0)return this.ranges.delete(e),this.ranges.set(e,t),this.source.reused(),t;let n=this.source.next();if(n===null)return null;let r=`ccb`+n.toString(36);return this.ranges.set(e,r),r}};function aae(e){return{band:()=>e=>({json:JSON.stringify(Zie(e)),value:null}),statusline:()=>(e,t)=>({json:t,value:null}),pane:()=>(e,t)=>({json:t,value:null}),tmuxStatus:()=>{let t=new iae(e);return e=>{let n=rae(e,t);return{json:JSON.stringify({ok:!0,tmuxStatus:n}),value:n}}}}}const oae=/^\d{1,15}\n?$/,sae=10**15-1,n7=`remove it and a new one is made, starting again from 0 (a click on a status row drawn before then may run a link drawn since)`;function cae(e){let{file:t,clock:n,retryMs:r,log:i}=e,a=0,o={kind:`ready`,next:0},s=0,c=0,l=0,u=0,d=0,f=()=>{try{let e=Math.max(lae(t),a),n=e+1024;if(n>sae)throw Error(`${t} holds ${e}, too near the last count for another block: ${n7}`);return dr(t,`${n}\n`,384),a=n,u++,o.kind===`faulted`&&i(`info`,`link ids: ${t} reserved again`),{kind:`ready`,next:e}}catch(e){d++;let t=`link ids: ${e.message}`;return(o.kind!==`faulted`||o.reason!==t)&&i(`error`,t),{kind:`faulted`,reason:t,clear:n.after(r,()=>o=f(),{unref:!0})}}};return{next(){return o.kind===`ready`&&o.next===a&&(o=f()),o.kind===`ready`?(s++,o.next++):null},reused:()=>void c++,evicted:()=>void l++,error:()=>o.kind===`faulted`?o.reason:null,stats:()=>({minted:s,reused:c,evicted:l,reservations:u,faults:d}),close(){o.kind===`faulted`&&o.clear(),o={kind:`closed`}}}}function lae(e){let t;try{t=h.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return 0;throw e}if(!oae.test(t))throw Error(`${e} holds ${JSON.stringify(t.slice(0,40))}, not a count: ${n7}`);return Number(t.trim())}const r7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,i7=`#{session_id} #{client_control_mode} #{pane_id}`;function a7(e){let t=new Set;for(let n of e.split(`
|
|
501
501
|
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function o7(e,t){let n=new Set;for(let r of e.split(`
|
|
502
|
-
`)){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
|
|
502
|
+
`)){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 uae(e,t){let n=new Map;for(let t of e.split(`
|
|
503
503
|
`)){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(`
|
|
504
|
-
`)){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
|
|
505
|
-
`,t:` `,r:`\r`,b:`\b`,a:`\x07`,v:`\v`,f:`\f`,0:`\0`},
|
|
506
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of x7)i.includes(C7(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,C7(Number(t)),T7(n)])]}const
|
|
507
|
-
`)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=F7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...I7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:fae(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,xae(n));if(r===null||this.closed)return null;let i=Sae(n,r,this.deps.owner,this.marks(e));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,S7(r),e])}),i!==n.status){let e=vae(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,b7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,c7(a)]])).kind===`ok`)&&(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,z7);if(r===null||this.closed)return;let{user:i}=g7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[hae(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${B7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,z7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=g7(t);return n.ours?{command:gae(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${B7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}async ask(e,t){let n=await this.run(e,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t){return t.length===0?E7:(this.writes++,this.run(e,D7(t)))}writeSync(e,t,n){return n.length===0?E7:(this.writes++,this.counted(t,e(t,D7(n))))}};const B7=e=>e===null?`unbound`:JSON.stringify(c7(e));function wae(e){try{return WS(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),V7=e=>({arity:e,keep:!1}),Tae={"--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":V7(`none`),"--background":V7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":V7(`optional`),"-c":V7(`none`),"--continue":V7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":V7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":V7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":V7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":V7(`optional`),"-h":V7(`none`),"--help":V7(`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":V7(`none`),"--print":V7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":V7(`optional`),"--resume":V7(`optional`),"--safe-mode":$(`none`),"--session-id":V7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":V7(`optional`),"--tmux":V7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":V7(`none`),"--version":V7(`none`),"-w":V7(`optional`),"--worktree":V7(`optional`)},H7={resume:`--resume`,fresh:`--session-id`};function Eae(e){return[H7[e.kind],e.sessionId]}const U7=e=>e.startsWith(`-`)&&e!==`-`;function W7(e,t){let n=G7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Dae(e,n.top)?{dir:e,args:[]}:{dir:e===null||G7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Dae=(e,t)=>e===t||e.startsWith(t+s.sep);function Oae(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!U7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=Tae[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=>!U7(e)):o.arity===`variadic`?kae(n.slice(r),e=>!U7(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 G7(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function kae(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const K7=`candybar-band@cc-candybar`,Aae=s.join(`bin`,`cc-candybar-native`),jae=EI(`/reload-plugins`);function Mae(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=LQ(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!hc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function q7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const J7=e=>({kind:`done`,said:e});function Y7(e){let t=LQ(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const Nae={band:{on:async(e,t,n)=>{let r=Tn(t.bundle);if(r===null)throw new R(`${hb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,Aae);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${K7} from ${r}`,finished:Pae(e,r,n)}},off:async()=>J7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=Y7(e.session),i=dn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${hb.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:e.inPane((e,r)=>Lae(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>q7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>J7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>q7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?J7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):J7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Un(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return J7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?J7(`no bar pane to close: ${r.reason}`):q7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>J7(`the daemon draws ${Y7(e).pane}'s bar in its status line`),off:async()=>J7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Pae(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,K7],i);let a=await e.inPane((e,t)=>RQ(n.claudeInput,t,jae)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${K7} from ${t} and typed /reload-plugins into ${o.pane}`}const Fae=new Set([Oo,OP]);function Iae(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Lae(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,fn(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${hb.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=Hae(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${hb.statusline.label} off and on again`);let s=Rae(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=Oae(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=Iae(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])=>Fae.has(e)),m=(e,t)=>hn(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...Eae(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=zae(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(W7(null,i.cwd),_))}let y=m(W7(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}\`, ${Bae[g.kind](e.sessionId)}, and its statusline follows lane B`}function Rae(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 zae(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Bae={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Vae={"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 Hae(e){let t=MQ(e);return t.kind===`ready`?FQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:NQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Vae[t.kind]}var Uae=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=gb.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return X7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return X7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new qs(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),Ks(r)},o;try{o=await Nae[t][n?`on`:`off`](Mae(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new qs(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function X7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const Wae=[`request`,`feed`],Z7=new WeakMap;let Gae=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Gae++;return Z7.set(e,n),n};var Kae=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 Wae){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}`,qae={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,mc(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function Jae(e){let t=qae[e.kind];return JSON.stringify(t(e))}var Yae=class{gathers=new o5;effects=new o5;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new qs(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new qs(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run(Jae(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},Xae=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}drawn(e,t,n,r){let i=this.since(e,t),a=r(i);return this.observe(e,t,a.frame.rows.some(e=>e.kind===`menu`),n),{...a,idleSince:i}}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++;return{sessions:this.sessions.size,armed:e}}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?kb(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,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 Zae(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=rr(o),u=ar(c,o),d=()=>st(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new N4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(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)}}),_=e.probe(g),v=e.storage(m),y=new Yae,b=new N1(y,v.session),x=new X1(b,m,v.history),S=Ti({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new Q4,w=new vne,T=e.doctorStores,E=new Fj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new tM(m),D=new Oc({watchers:E,logger:m,clock:i}),te=new bM({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=hie({launcher:g,host:c,pricing:e.pricing({cacheRoot:In(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{gitProvider:k,usageStore:ne,tmuxService:A,hostService:re,managedStorage:ie}=O,ae=new Fie,oe=new Gte,se=new Xae({clock:i,now:d,close:async(e,t)=>{await U6({kind:`menu-idle`,session:e,idle:t},we)},failed:(e,t)=>Z6(m,`menu-idle`,`session=${e}`,t)}),ce={to:o.name,signer:e.linkSigner},le=new ec({supersede:(e,t)=>ie.supersede(e,t),launch:g.launch,log:m,clock:i}),ue=new Uae({edge:e.laneEdge(g,e=>pe.following(e),f.signal,_),host:{bundle:t.path,node:t.node,home:o,preload:cs(t.path,c)},log:m,latest:e=>{let t=pe.latest(e);return t===null?null:wQ(t)},paneOrder:(e,t)=>y.performing({kind:`pane`,tmux:e},t)}),de=new Cae({edge:{run:(e,t)=>Ws(g,{socket:e},`tmux-status`,t)},subscribe:(e,t)=>pe.subscribe(e,t),sessionInPane:(e,t)=>pe.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[...Object.entries(Un(o)).map(([e,t])=>`${e}=${cn(t)}`),...[...t.node,t.path].map(cn),`url-handle`].join(` `),owner:l.socket,name:o.name,signer:e.linkSigner,log:m}),fe=iae({file:l.linkIds,clock:i,retryMs:xZ.still,log:m}),pe=new DZ({render:(e,t,n)=>fQ(we,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>b.revision(e),t),lanes:e=>mQ(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:()=>ee.totals(),periods:xZ,encoders:tae(fe),clock:i,instant:d,log:m}),me=new sae({clock:i,listPanes:e=>Ws(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,r7]),listClients:e=>Ws(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,i7]),sockets:()=>new Set(pe.watched().flatMap(({req:e})=>he(e))),onAnswer:(e,t)=>de.answered(e,t),onChange:e=>pe.wakeWhere(`visibility`,t=>he(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function he({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ge=new Kae,_e=pre(),{cache:ve,recorder:ye}=iQ(e=>new Nie({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,storage:ie,links:ce,gates:s,facts:Bie({providers:O,update:()=>_e.get(),runs:te}),source:Hie({providers:O,sessionState:b,history:e=>x.depth(e),navigation:(e,t)=>ae.depth(e,b,s.state.gateFor(t))})},{budgetBytes:()=>vie(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Sie(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`),...e}}),m);D.subscribe(e=>{switch(e.kind){case`period`:E.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 be=60*1e3,xe=hre({clock:i,targets:t.targets,intervalMs:be,filesystem:e.filesystem,held:()=>Se.running(),exit:()=>a(0),log:m}),Se=fre({fact:_e,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:Z8(l.state,t.path),intervalMs:be,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>xe.checkNow(),log:m}),Ce={gates:s,sessionState:b,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:y,clickLanded:e=>se.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>Se.act(),doctor:e.doctorEdge(g,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:T,probes:C,clients:w,bundle:t.path,serving:()=>S.serving(),claudeInput:e.claudeInput(g),history:x,navigation:ae,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:ce,runs:le,lanes:{of:(e,t)=>hQ(we,e,t),clicked:(e,t,n)=>TQ(we,e,t,n),arrived:e=>SQ(we,e),setup:e=>ue.setup(e)},diagnosticCopy:(e,t,n)=>ve.drawnCopy(e,t,n)},we={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:(e,t,n,r)=>EQ(we,e,t,n,r),effectSessions:oe,menuIdle:se,journalTurns:y,links:ce,runs:le,sourceRuns:te,laneSetups:ue,tmuxStatusLines:de,frameFeeds:pe,linkIds:fe,renderWarnings:ge,renderCache:ve,recorder:ye,updateWatch:Se,limits:S,verbCtx:Ce};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),M8(we,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),N8(we,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Ce.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),xe.arm(),Se.arm(),S.arm()},close(e){let t=[[`journalTurns close`,()=>y.close()],[`tmuxStatusLines restore`,()=>de.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>ue.close()],[`frameFeeds close`,()=>pe.close()],[`linkIds close`,()=>fe.close()],[`menuIdle dispose`,()=>se.dispose()],[`updateWatch close`,()=>Se.close()],[`binaryWatch close`,()=>xe.close()],[`limits disarm`,()=>S.disarm()],[`recorder close`,()=>ye.close()],[`renderCache close`,()=>ve.close()],[`gitService close`,()=>k.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>A.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>le.close()],[`sourceRuns close`,()=>te.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>D.close()],[`watcherRegistry close`,()=>E.closeAll()],[`sessionState close`,()=>b.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function Qae(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 $ae=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=h.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 Qae(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=tt(this.clock,n);try{await h.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await h.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 h.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await h.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${tt(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{h.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);h.writeFileSync(n,r,{mode:384}),h.chmodSync(n,384),h.rmSync(this.writingPath,{force:!0}),h.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,tt(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=${tt(this.clock,n)}ms held=${r}ms`)}};function eoe(e,t,n){return{session:new $ae(e.sessionState,n,500,t),history:v0(e.settingsHistory,e.storedRoot,t)}}function e9(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function t9(e,t){try{return h.accessSync(e,t),h.statSync(e).isFile()}catch{return!1}}function toe(e){try{return h.realpathSync(e)}catch{return s.resolve(e)}}function noe(e,t,n){let r=e9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const n9=2e3;async function r9(e,t,n,r){let i=await Ws(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=_t(t,t.stdout);throw Error(`${e} failed (${vt(t)}${n===``?``:`: ${n}`})`)}function roe(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 ioe=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function aoe(e,t){return e.split(`
|
|
508
|
-
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return
|
|
509
|
-
`);async function loe(e,t){if(process.platform===`linux`)return{executable:await h.promises.readlink(`/proc/${t}/exe`),argv:(await h.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await h.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`,coe,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 Ws(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 uoe(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 loe(e,i),s=N0(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await h.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:soe(a,i,n)}}function doe(e,t,n,r,i){let a=e=>rt(r,e,n);return{claudeInput:UQ(e),barPanes:async t=>aoe(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:b0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>h.existsSync(e),presence:Rz,paneClaude:t=>uoe(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=>noe(e,e=>t9(e,h.constants.X_OK),toe),onPath:(e,t)=>{let n=e9(e,t,e=>t9(e,h.constants.X_OK));return n===null?null:h.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`?roe(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,VQ(t.pane,`cc-candybar-lane`,[]),n)}}const foe=/^[0-9a-f]{64}$/;function s9(e,t){return le(`sha256`,e).update(JSON.stringify(t)).digest()}const c9=e=>[e.sessionId,e.action,e.declaration,e.evaluated],l9=e=>[FS,e];function poe(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=t=>s9(e,t).toString(`hex`),n=(t,n)=>foe.test(n)&&fe(Buffer.from(n,`hex`),s9(e,t));return{sign:e=>t(c9(e)),verify:(e,t)=>n(c9(e),t),signBinding:e=>t(l9(e)),verifyBinding:(e,t)=>n(l9(e),t)}}function u9(e){return s.join(e,`link.key`)}function d9(e){let t,n=()=>t??=moe(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t),signBinding:e=>n().signBinding(e),verifyBinding:(e,t)=>n().verifyBinding(e,t)}}function moe(e){let t;try{t=h.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;hoe(e),t=h.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 poe(t)}function hoe(e){h.mkdirSync(s.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ue(6).toString(`hex`)}`;h.writeFileSync(t,ue(32),{mode:384,flag:`wx`});try{h.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{h.unlinkSync(t)}}function goe(e,t,n){return{daemonLog:t,launcher:e=>tn(e,n),storage:t=>eoe(e,t,n),doctorStores:e4(e.state),doctorEdge:f4,claudeInput:UQ,probe:js,laneEdge:(e,t,r,i)=>doe(e,t,r,n,i),linkSigner:d9(u9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>ji(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>Dre({...e,clock:n}),filesystem:Pn}}function f9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function _oe(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(Ir(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,lQ)}),u=Rr(r=>{let i=jr(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):e.kind===`subscribe`?d(e.sessionId,e.lane):f(e.start))}).catch(t=>{e.log(`error`,`handler threw: ${k(t)}`),c&&o(uQ(t),null,lQ)}).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,lQ)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=f9(t),s=e.subscribe(n,{lane:i,frame:e=>o(Lr(e.json)),refused:e=>t.end(Ir(e)),drawing:()=>!0});r=!0,t.on(`close`,s)},f=n=>{if(r||t.destroyed)return;l(),t.off(`data`,u);let i=new AbortController;t.on(`close`,()=>i.abort()),n(i.signal).then(e=>o(e.resp,e.exitAfterFlush,e.delivered),t=>{e.log(`error`,`held request threw: ${k(t)}`),o(uQ(t),null,lQ)})};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const p9=`CC_CANDYBAR_PARENT_PID`;function voe(e){let t=e[p9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${p9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function yoe(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let m9=null,h9=null,g9=null,_9=null;function v9(){if(_9===null)throw Error(`runDaemon has not started`);return _9}function y9(e,t){v9().log.log(e,t)}function boe(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:En(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function xoe(e){let n=rr(e.home);_9={world:e,paths:n,log:new Bs(n.log,e.clock)},t.on(`uncaughtException`,e=>{y9(`error`,`uncaughtException: ${e.stack||e.message}`),C9(1)}),t.on(`unhandledRejection`,e=>{y9(`error`,`unhandledRejection: ${String(e)}`),C9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{y9(`info`,`received ${e}, shutting down`),C9(0)});Soe().catch(b9)}function b9(e){y9(`error`,`refusing to boot: ${k(e)}`),C9(1)}async function Soe(){let{world:e,paths:n,log:r}=v9(),{host:i,home:a}=e,o=_i(i.env);a.kind===`main`&&a.legacySocket!==null&&y9(`warn`,`CC_CANDYBAR_SOCKET=${a.legacySocket} is honoured for one more release; a renderer is named by CC_CANDYBAR_HOME and CC_CANDYBAR_NAME instead`),m9=await uee(t.pid,js(e.launcher).startTime);let s=await mee(gee(e,m9,Xn(i),n.socket!==Hn(Le)));if(!s.decision.allow){y9(`warn`,`fork-bomb breaker: ${s.decision.reason}; refusing to boot`),C9(1);return}h9=s.registryPath,h.mkdirSync(n.state,{recursive:!0}),Gn(n.socket);let c=Zae({...goe(n,r,e.clock),bundle:boe(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Lz(),exit:C9});g9=c,yoe({clock:e.clock,anchor:voe(i.env),probe:js(e.launcher),onOrphaned:e=>{y9(`info`,`parent watchdog: ${e}; shutting down`),C9(0)}}),x9(c,m.createServer(e=>_oe(c,e)),n.socket,!1)}function x9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){y9(`error`,`server error: ${a.message}`),C9(1);return}if(i){y9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Coe(e,n,r).catch(b9)}),n.listen(r,()=>woe(e,r))}async function Coe(e,n,r){let i=await Es(Ds(Kn(r)),(t,n)=>Ms(t,n,js(e.launcher)));if(i.kind===`attach-and-exit`){y9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}y9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{h.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){y9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),C9(1);return}}x9(e,n,r,!0)}function woe(e,n){let r=As(n);if(r.kind!==`present`){y9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),C9(0);return}Eoe(n);try{h.chmodSync(n,384)}catch(e){y9(`warn`,`chmod socket failed: ${e.message}`)}y9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${P(pe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${P(e.memoryLimitBytes)}MB`),Bi(v9().paths.spawnBackoff),e.arm(),Toe(n,r.identity)}function Toe(e,n){cee({bound:n,myPid:t.pid,readIdentity:()=>As(e),readLease:()=>Ds(Kn(e)),shutdown:e=>C9(e),log:y9,clock:v9().world.clock}).arm()}function Eoe(e){let n=Os(Kn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:m9});n!==null&&y9(`warn`,`lease write failed: ${n}`)}const Doe=e=>(t,n)=>Us(e,{socket:t},`tmux-status`,n);let S9=!1;function C9(e){S9||(S9=!0,v9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),g9?.close(Doe(v9().world.launcher)),ks(v9().paths.lease,t.pid),h9!==null&&hee(h9,t.pid,Ps,e=>h.unlinkSync(e)),t.exit(e))}function Ooe(e,t){let n=[],r=10;for(let t=0;t<e.length;t++){let i=e[t];if(i===`--seconds`){let n=e[++t];if(n===void 0)return{ok:!1,problem:`--seconds needs a number after it`};let i=Nr(Number(n));if(!i.ok)return{ok:!1,problem:`--seconds ${JSON.stringify(n)} ${i.problem}`};r=i.seconds}else if(i!==void 0&&!i.startsWith(`-`))n.push(i);else return{ok:!1,problem:`unexpected argument ${JSON.stringify(i)}`}}let[i,a,...o]=n;return i===void 0||a===void 0||o.length>0?{ok:!1,problem:`usage: cc-candybar record <session-id> <path> [--seconds N]`}:{ok:!0,args:{session:i,path:f(t,a),seconds:r}}}function koe(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${Jr(e)}\n`,code:1};let{path:n,lines:r,answers:i,daemonClosed:a}=e.value,o=`the daemon closed before ${t}s ran out`;return i===0?{stdout:``,stderr:a?`record: ${n}: ${o}, and no request had been answered, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered in ${t}s, so there is nothing to replay: the session was idle, or its statusline is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers\n`,stderr:a?`record: ${o}: the file holds what came before.\n`:``,code:0}}async function Aoe(e,t,n){let r=Ooe(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return koe(await Vr(e,()=>({kind:`record`,session:i,path:a,seconds:o}),{connectMs:200,budgetMs:o*1e3+2e3},e=>`recorded`in e?e.recorded:void 0),o)}const joe={connectMs:200,budgetMs:500};async function Moe(e,t,n){return Noe(t,await Poe(e,t),n.includes(`--json`))}function Noe(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
510
|
-
`:
|
|
511
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
504
|
+
`)){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 dae=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: ${k(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:o7(t.stdout,a7(n.stdout)),status:uae(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),!fae(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 fae(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 s7(e){return`"${e.replace(/[\\"$~]/g,e=>`\\${e}`)}"`}function c7(e){return e.map(e=>e.map(l7).join(` `)).join(` ; `)}const l7=e=>typeof e==`string`?s7(e):`{ ${c7(e.block)} }`;function pae(e){return e.map(e=>e.map(l7).join(` `)).join(` \\; `)}const mae={n:`
|
|
505
|
+
`,t:` `,r:`\r`,b:`\b`,a:`\x07`,v:`\v`,f:`\f`,0:`\0`},hae=(e,t)=>e.startsWith(`\\;`,t)&&(e[t+2]??` `)===` `;function u7(e){let t=0,n=n=>e[t]===n&&(e[t+1]??` `)===` `,r=()=>{let n=[],r=e=>{n.push(...Buffer.from(e,`utf8`))},i=null;for(;t<e.length;){let a=e[t];if(i===null&&(a===` `||a===`;`))break;if(a===i)i=null,t++;else if(i===null&&(a===`"`||a===`'`))i=a,t++;else if(a===`\\`&&t+1<e.length){let i=/^[0-7]{3}/.exec(e.slice(t+1,t+4)),a=e[t+1];i===null?(r(mae[a]??a),t+=2):(n.push(parseInt(i[0],8)),t+=4)}else{let n=String.fromCodePoint(e.codePointAt(t));r(n),t+=n.length}}return Buffer.from(n).toString(`utf8`)},i=a=>{let o=[[]];for(;t<e.length;)if(e[t]===` `)t++;else if(e[t]===`;`||!a&&hae(e,t))o.push([]),t+=e[t]===`;`?1:2;else if(a&&n(`}`)){t++;break}else n(`{`)?(t++,o.at(-1).push({block:i(!0)})):o.at(-1).push(r());return o.filter(e=>e.length>0)};return i(!1)}const d7=[`-T`,`root`,`MouseDown1Status`],f7=`@cc-candybar-renderer`,p7=`@cc-candybar-click`;function gae(e,t,n,r){return`${e} ${WS(t,MS,BS([n,r]))}`}const m7=`#{m:ccb*,#{mouse_status_range}}`;function _ae(e){let t=`run-shell -b ${s7(`#{${p7}}/#{s/%//:pane_id}/#{q:mouse_status_range}`)}`,n=`display-message ${s7(`cc-candybar: no renderer takes clicks on this row: the one that drew it is older than this binding`)}`;return[`bind-key`,...d7,`if-shell`,`-F`,m7,`if-shell -F ${s7(`#{${p7}}`)} ${s7(t)} ${s7(n)}`,...e===null?[]:[c7(e)]]}const vae=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m;function h7(e){let[t,...n]=e;if(t===void 0||n.length>0||t[0]!==`if-shell`)return;let r=t.slice(1);for(;typeof r[0]==`string`&&r[0].startsWith(`-`);)r=r.slice(1);if(r[0]!==m7)return;let i=r[2],a=i===void 0?[]:typeof i==`string`?u7(i):i.block;return a.length>0?a:null}function g7(e){let t=vae.exec(e)?.[1],n=t===void 0?null:u7(t),r=n!==null&&h7(n)!==void 0;for(;n!==null;){let e=h7(n);if(e===void 0)break;n=e}return{ours:r,user:n}}const _7=`#{S:#{?#{!=:#{${f7}},},1,}}`;function yae(e){return[`if-shell`,`-F`,_7,`${c7([_ae(e)])} ; display-message -p ccb:bound`]}function bae(e){return[`if-shell`,`-F`,_7,`display-message -p ccb:held`,`${e===null?`unbind-key ${d7.join(` `)}`:`bind-key ${d7.join(` `)} ${pae(e)}`} ; display-message -p ccb:restored`]}const v7=pb.tmuxStatus.rows,y7=`@cc-candybar-status-prior`,b7=`@cc-candybar-status-wrote`,x7=Array.from({length:v7},(e,t)=>t),S7=e=>`@cc-candybar-row-${e}`,xae=e=>`#[fill=terminal]#{${S7(e)}}`,C7=e=>`status-format[${e}]`;function Sae(e){return e===0?`off`:e===1?`on`:String(e)}function w7(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 Cae(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 T7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}const E7={kind:`ok`,stdout:``};function D7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}const O7=`ccb:separator`;function k7(e){return D7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,O7],e]))}function A7(e,t){let n=e.split(`${O7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const j7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],wae=e=>[`show-options`,`-g`,`-q`,`-v`,e],M7=e=>[[`show-options`,`-t`,e],j7(e,`status`),...x7.map(t=>j7(e,C7(t)))];function N7(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
506
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of x7)i.includes(C7(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,C7(Number(t)),T7(n)])]}const Tae=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...M7(e),...x7.map(e=>wae(C7(e))),j7(e,y7),j7(e,b7)];function F7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:w7(t)}catch(e){return{kind:`theirs`,why:`${y7} 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,f7,t.name],[`set-option`,`-t`,e,p7,t.click]];function Eae(e,t,n,r){let[i=``,...a]=t,o=N7(a.slice(0,2+v7)),s=a.slice(2+v7,2+2*v7),[c=``,l=``]=a.slice(2+2*v7);if(c!==``){let t=F7(c,l,n);return t.kind===`theirs`?t:{...t,commands:I7(e,r)}}let u=w7(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:v7-u},(e,t)=>[u+t,xae(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,y7,JSON.stringify(p)],...I7(e,r),...P7(e,f)]}}const L7=e=>[...M7(e),j7(e,b7)];function R7(e,t,n){let r=N7(n.slice(0,2+v7)),i=n[2+v7]??``,a=[],o=[];if(Cae(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,C7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,T7(t.status)]):o.push(`status`)),a.push(...x7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,S7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,y7],[`set-option`,`-q`,`-u`,`-t`,e,b7],[`set-option`,`-q`,`-u`,`-t`,e,f7],[`set-option`,`-q`,`-u`,`-t`,e,p7]),{commands:a,kept:o}}const z7=[[`list-keys`,`-T`,`root`]];var Dae=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||!hc(r,i))&&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=e.value,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)}if(n.binding===`none`)continue;n.binding=`none`;let r=this.askSync(e,t,z7);if(r===null)continue;let i=this.bindingRestore(t,r[0]??``);if(i===null)continue;let a=this.writeSync(e,t,[i.command]);this.saidBindingRestore(t,a,i.user)}}linkAt(e){let t=Oae(e),[n,r,i,a,...o]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a===void 0||o.length>0)return{kind:`refused`,reason:`${MS} needs <socket>/<mac>/<pane>/<range>, got ${JSON.stringify(e)}`};if(!this.deps.signer.verifyBinding(n,r))return{kind:`refused`,reason:`a status-line click on ${JSON.stringify(n)} whose mac is not this renderer's binding's`};let s=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${i}`)?.frame?.links,c=s!==void 0&&Object.hasOwn(s,a)?s[a]:void 0;return c===void 0?{kind:`refused`,reason:`pane %${i}'s status line draws no link ${a} now`}:{kind:`link`,url:c}}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:`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,v7-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#{${y7}}\t#{${b7}}`]);if(n.kind===`ok`){let r=this.marks(e),i=[];for(let a of n.stdout.split(`
|
|
507
|
+
`)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=F7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...I7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:gae(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,Tae(n));if(r===null||this.closed)return null;let i=Eae(n,r,this.deps.owner,this.marks(e));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,S7(r),e])}),i!==n.status){let e=Sae(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,b7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,c7(a)]])).kind===`ok`)&&(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,z7);if(r===null||this.closed)return;let{user:i}=g7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[yae(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${B7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,z7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=g7(t);return n.ours?{command:bae(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${B7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}async ask(e,t){let n=await this.run(e,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t){return t.length===0?E7:(this.writes++,this.run(e,D7(t)))}writeSync(e,t,n){return n.length===0?E7:(this.writes++,this.counted(t,e(t,D7(n))))}};const B7=e=>e===null?`unbound`:JSON.stringify(c7(e));function Oae(e){try{return VS(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),V7=e=>({arity:e,keep:!1}),kae={"--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":V7(`none`),"--background":V7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":V7(`optional`),"-c":V7(`none`),"--continue":V7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":V7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":V7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":V7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":V7(`optional`),"-h":V7(`none`),"--help":V7(`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":V7(`none`),"--print":V7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":V7(`optional`),"--resume":V7(`optional`),"--safe-mode":$(`none`),"--session-id":V7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":V7(`optional`),"--tmux":V7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":V7(`none`),"--version":V7(`none`),"-w":V7(`optional`),"--worktree":V7(`optional`)},Aae={resume:`--resume`,fresh:`--session-id`};function jae(e){return[Aae[e.kind],e.sessionId]}const H7=e=>e.startsWith(`-`)&&e!==`-`;function U7(e,t){let n=W7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Mae(e,n.top)?{dir:e,args:[]}:{dir:e===null||W7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Mae=(e,t)=>e===t||e.startsWith(t+s.sep);function Nae(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!H7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=kae[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=>!H7(e)):o.arity===`variadic`?Pae(n.slice(r),e=>!H7(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 W7(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function Pae(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const G7=`candybar-band@cc-candybar`,Fae=s.join(`bin`,`cc-candybar-native`),Iae=SI(`/reload-plugins`);function Lae(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=LQ(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!hc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function K7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const q7=e=>({kind:`done`,said:e});function J7(e){let t=LQ(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const Rae={band:{on:async(e,t,n)=>{let r=Tn(t.bundle);if(r===null)throw new R(`${pb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,Fae);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${G7} from ${r}`,finished:zae(e,r,n)}},off:async()=>q7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=J7(e.session),i=dn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${pb.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:e.inPane((e,r)=>Hae(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>K7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>q7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>K7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?q7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):q7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Un(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return q7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?q7(`no bar pane to close: ${r.reason}`):K7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>q7(`the daemon draws ${J7(e).pane}'s bar in its status line`),off:async()=>q7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function zae(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,G7],i);let a=await e.inPane((e,t)=>RQ(n.claudeInput,t,Iae)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${G7} from ${t} and typed /reload-plugins into ${o.pane}`}const Bae=new Set([Oo,TP]);function Vae(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Hae(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,fn(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}) — ${pb.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=qae(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${pb.statusline.label} off and on again`);let s=Uae(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=Nae(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=Vae(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])=>Bae.has(e)),m=(e,t)=>hn(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...jae(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=Wae(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(U7(null,i.cwd),_))}let y=m(U7(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}\`, ${Gae[g.kind](e.sessionId)}, and its statusline follows lane B`}function Uae(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 Wae(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Gae={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Kae={"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 qae(e){let t=MQ(e);return t.kind===`ready`?FQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:NQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Kae[t.kind]}var Jae=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=mb.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return Y7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return Y7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new qs(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),Ks(r)},o;try{o=await Rae[t][n?`on`:`off`](Lae(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new qs(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function Y7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const Yae=[`request`,`feed`],X7=new WeakMap;let Xae=0;const Z7=e=>{let t=X7.get(e);if(t!==void 0)return t;let n=Xae++;return X7.set(e,n),n};var Zae=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(Q7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Z7(n.config),i=[];for(let n of Yae){let a=this.records.get(Q7(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=Q7(e,t);this.records.delete(a),this.records.set(a,{generation:Z7(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const Q7=(e,t)=>`${t}\0${e}`,Qae={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,mc(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function $ae(e){let t=Qae[e.kind];return JSON.stringify(t(e))}var eoe=class{gathers=new o5;effects=new o5;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new qs(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new qs(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run($ae(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},toe=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}drawn(e,t,n,r){let i=this.since(e,t),a=r(i);return this.observe(e,t,a.frame.rows.some(e=>e.kind===`menu`),n),{...a,idleSince:i}}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++;return{sessions:this.sessions.size,armed:e}}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?Db(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,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 noe(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=rr(o),u=ar(c,o),d=()=>st(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new N4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(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)}}),_=e.probe(g),v=e.storage(m),y=new eoe,b=new N1(y,v.session),x=new X1(b,m,v.history),S=Ti({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new Q4,w=new xne,T=e.doctorStores,E=new Mj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new Qj(m),D=new Oc({watchers:E,logger:m,clock:i}),te=new _M({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=yie({launcher:g,host:c,pricing:e.pricing({cacheRoot:In(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{gitProvider:k,usageStore:ne,tmuxService:A,hostService:re,managedStorage:ie}=O,ae=new zie,oe=new Jte,se=new toe({clock:i,now:d,close:async(e,t)=>{await U6({kind:`menu-idle`,session:e,idle:t},we)},failed:(e,t)=>Z6(m,`menu-idle`,`session=${e}`,t)}),ce={to:o.name,signer:e.linkSigner},le=new ec({supersede:(e,t)=>ie.supersede(e,t),launch:g.launch,log:m,clock:i}),ue=new Jae({edge:e.laneEdge(g,e=>pe.following(e),f.signal,_),host:{bundle:t.path,node:t.node,home:o,preload:cs(t.path,c)},log:m,latest:e=>{let t=pe.latest(e);return t===null?null:wQ(t)},paneOrder:(e,t)=>y.performing({kind:`pane`,tmux:e},t)}),de=new Dae({edge:{run:(e,t)=>Ws(g,{socket:e},`tmux-status`,t)},subscribe:(e,t)=>pe.subscribe(e,t),sessionInPane:(e,t)=>pe.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[...Object.entries(Un(o)).map(([e,t])=>`${e}=${cn(t)}`),...[...t.node,t.path].map(cn),`url-handle`].join(` `),owner:l.socket,name:o.name,signer:e.linkSigner,log:m}),fe=cae({file:l.linkIds,clock:i,retryMs:yZ.still,log:m}),pe=new TZ({render:(e,t,n)=>fQ(we,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>b.revision(e),t),lanes:e=>mQ(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:()=>ee.totals(),periods:yZ,encoders:aae(fe),clock:i,instant:d,log:m}),me=new dae({clock:i,listPanes:e=>Ws(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,r7]),listClients:e=>Ws(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,i7]),sockets:()=>new Set(pe.watched().flatMap(({req:e})=>he(e))),onAnswer:(e,t)=>de.answered(e,t),onChange:e=>pe.wakeWhere(`visibility`,t=>he(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function he({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ge=new Zae,_e=_re(),{cache:ve,recorder:ye}=nQ(e=>new Lie({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,storage:ie,links:ce,gates:s,facts:Wie({providers:O,update:()=>_e.get(),runs:te}),source:Kie({providers:O,sessionState:b,history:e=>x.depth(e),navigation:(e,t)=>ae.depth(e,b,s.state.gateFor(t))})},{budgetBytes:()=>Sie(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Eie(e,n,r));for(let e of t)pe.wake(e,`reload`)},onViewChanged:e=>pe.wake(e,`data`),...e}}),m);D.subscribe(e=>{switch(e.kind){case`period`:E.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 be=60*1e3,xe=yre({clock:i,targets:t.targets,intervalMs:be,filesystem:e.filesystem,held:()=>Se.running(),exit:()=>a(0),log:m}),Se=gre({fact:_e,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:Z8(l.state,t.path),intervalMs:be,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>xe.checkNow(),log:m}),Ce={gates:s,sessionState:b,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:y,clickLanded:e=>se.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>Se.act(),doctor:e.doctorEdge(g,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:T,probes:C,clients:w,bundle:t.path,serving:()=>S.serving(),claudeInput:e.claudeInput(g),history:x,navigation:ae,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:ce,runs:le,lanes:{of:(e,t)=>hQ(we,e,t),clicked:(e,t,n)=>TQ(we,e,t,n),arrived:e=>SQ(we,e),setup:e=>ue.setup(e)},diagnosticCopy:(e,t,n)=>ve.drawnCopy(e,t,n)},we={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:(e,t,n,r)=>EQ(we,e,t,n,r),effectSessions:oe,menuIdle:se,journalTurns:y,links:ce,runs:le,sourceRuns:te,laneSetups:ue,tmuxStatusLines:de,frameFeeds:pe,linkIds:fe,renderWarnings:ge,renderCache:ve,recorder:ye,updateWatch:Se,limits:S,verbCtx:Ce};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),M8(we,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),N8(we,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),pe.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Ce.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),xe.arm(),Se.arm(),S.arm()},close(e){let t=[[`journalTurns close`,()=>y.close()],[`tmuxStatusLines restore`,()=>de.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>ue.close()],[`frameFeeds close`,()=>pe.close()],[`linkIds close`,()=>fe.close()],[`menuIdle dispose`,()=>se.dispose()],[`updateWatch close`,()=>Se.close()],[`binaryWatch close`,()=>xe.close()],[`limits disarm`,()=>S.disarm()],[`recorder close`,()=>ye.close()],[`renderCache close`,()=>ve.close()],[`gitService close`,()=>k.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>A.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>le.close()],[`sourceRuns close`,()=>te.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>D.close()],[`watcherRegistry close`,()=>E.closeAll()],[`sessionState close`,()=>b.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function roe(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 ioe=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=h.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 roe(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=tt(this.clock,n);try{await h.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await h.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 h.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await h.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${tt(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{h.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);h.writeFileSync(n,r,{mode:384}),h.chmodSync(n,384),h.rmSync(this.writingPath,{force:!0}),h.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,tt(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=${tt(this.clock,n)}ms held=${r}ms`)}};function aoe(e,t,n){return{session:new ioe(e.sessionState,n,500,t),history:v0(e.settingsHistory,e.storedRoot,t)}}function $7(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function e9(e,t){try{return h.accessSync(e,t),h.statSync(e).isFile()}catch{return!1}}function ooe(e){try{return h.realpathSync(e)}catch{return s.resolve(e)}}function soe(e,t,n){let r=$7(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const t9=2e3;async function n9(e,t,n,r){let i=await Ws(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function r9(e,t){if(t.ok)return t.stdout;let n=_t(t,t.stdout);throw Error(`${e} failed (${vt(t)}${n===``?``:`: ${n}`})`)}function coe(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 loe=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function uoe(e,t){return e.split(`
|
|
508
|
+
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return loe.exec(r.join(` `))?.[1]===t?[n]:[]})}const doe=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function foe(e,t,n){for(let r of P0(N0(e),t)){if(r.command.split(` `).some(e=>doe.test(e)))return!0;if(r.pid===n)return!1}return!1}const poe=[`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(`
|
|
509
|
+
`);async function moe(e,t){if(process.platform===`linux`)return{executable:await h.promises.readlink(`/proc/${t}/exe`),argv:(await h.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await h.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=r9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,poe,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function i9(e,t,n){return r9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function a9(e,t){let n=await Ws(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 i9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function hoe(e,t){let{panePid:n,cwd:r,foreground:i}=await a9(e,t),a=await i9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await moe(e,i),s=N0(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await h.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:foe(a,i,n)}}function goe(e,t,n,r,i){let a=e=>rt(r,e,n);return{claudeInput:UQ(e),barPanes:async t=>uoe(await n9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await n9(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 n9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void r9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:b0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>h.existsSync(e),presence:Pz,paneClaude:t=>hoe(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+t9;for(;;){let o=await a9(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 ${t9/1e3} s`);await a(100)}},launcherNode:e=>soe(e,e=>e9(e,h.constants.X_OK),ooe),onPath:(e,t)=>{let n=$7(e,t,e=>e9(e,h.constants.X_OK));return n===null?null:h.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`?coe(i.stdout):null;return a===null?(r9(`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 n9(e,t,VQ(t.pane,`cc-candybar-lane`,[]),n)}}const _oe=/^[0-9a-f]{64}$/;function o9(e,t){return le(`sha256`,e).update(JSON.stringify(t)).digest()}const s9=e=>[e.sessionId,e.action,e.declaration,e.evaluated],c9=e=>[MS,e];function voe(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=t=>o9(e,t).toString(`hex`),n=(t,n)=>_oe.test(n)&&fe(Buffer.from(n,`hex`),o9(e,t));return{sign:e=>t(s9(e)),verify:(e,t)=>n(s9(e),t),signBinding:e=>t(c9(e)),verifyBinding:(e,t)=>n(c9(e),t)}}function l9(e){return s.join(e,`link.key`)}function u9(e){let t,n=()=>t??=yoe(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t),signBinding:e=>n().signBinding(e),verifyBinding:(e,t)=>n().verifyBinding(e,t)}}function yoe(e){let t;try{t=h.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;boe(e),t=h.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 voe(t)}function boe(e){h.mkdirSync(s.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ue(6).toString(`hex`)}`;h.writeFileSync(t,ue(32),{mode:384,flag:`wx`});try{h.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{h.unlinkSync(t)}}function xoe(e,t,n){return{daemonLog:t,launcher:e=>tn(e,n),storage:t=>aoe(e,t,n),doctorStores:e4(e.state),doctorEdge:f4,claudeInput:UQ,probe:js,laneEdge:(e,t,r,i)=>goe(e,t,r,n,i),linkSigner:u9(l9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>ji(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>jre({...e,clock:n}),filesystem:Pn}}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 Soe(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(Ir(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,lQ)}),u=Rr(r=>{let i=jr(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):e.kind===`subscribe`?d(e.sessionId,e.lane):f(e.start))}).catch(t=>{e.log(`error`,`handler threw: ${k(t)}`),c&&o(uQ(t),null,lQ)}).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,lQ)}),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=>o(Lr(e.json)),refused:e=>t.end(Ir(e)),drawing:()=>!0});r=!0,t.on(`close`,s)},f=n=>{if(r||t.destroyed)return;l(),t.off(`data`,u);let i=new AbortController;t.on(`close`,()=>i.abort()),n(i.signal).then(e=>o(e.resp,e.exitAfterFlush,e.delivered),t=>{e.log(`error`,`held request threw: ${k(t)}`),o(uQ(t),null,lQ)})};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 Coe(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 woe(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 Toe(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:En(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function Eoe(e){let n=rr(e.home);g9={world:e,paths:n,log:new Bs(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)});Doe().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${k(e)}`),S9(1)}async function Doe(){let{world:e,paths:n,log:r}=_9(),{host:i,home:a}=e,o=_i(i.env);a.kind===`main`&&a.legacySocket!==null&&v9(`warn`,`CC_CANDYBAR_SOCKET=${a.legacySocket} is honoured for one more release; a renderer is named by CC_CANDYBAR_HOME and CC_CANDYBAR_NAME instead`),p9=await uee(t.pid,js(e.launcher).startTime);let s=await mee(gee(e,p9,Xn(i),n.socket!==Hn(Le)));if(!s.decision.allow){v9(`warn`,`fork-bomb breaker: ${s.decision.reason}; refusing to boot`),S9(1);return}m9=s.registryPath,h.mkdirSync(n.state,{recursive:!0}),Gn(n.socket);let c=noe({...xoe(n,r,e.clock),bundle:Toe(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Nz(),exit:S9});h9=c,woe({clock:e.clock,anchor:Coe(i.env),probe:js(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,m.createServer(e=>Soe(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}Ooe(e,n,r).catch(y9)}),n.listen(r,()=>koe(e,r))}async function Ooe(e,n,r){let i=await Es(Ds(Kn(r)),(t,n)=>Ms(t,n,js(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{h.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 koe(e,n){let r=As(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}joe(n);try{h.chmodSync(n,384)}catch(e){v9(`warn`,`chmod socket failed: ${e.message}`)}v9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${P(pe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${P(e.memoryLimitBytes)}MB`),Bi(_9().paths.spawnBackoff),e.arm(),Aoe(n,r.identity)}function Aoe(e,n){cee({bound:n,myPid:t.pid,readIdentity:()=>As(e),readLease:()=>Ds(Kn(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function joe(e){let n=Os(Kn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const Moe=e=>(t,n)=>Us(e,{socket:t},`tmux-status`,n);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(Moe(_9().world.launcher)),ks(_9().paths.lease,t.pid),m9!==null&&hee(m9,t.pid,Ps,e=>h.unlinkSync(e)),t.exit(e))}function Noe(e,t){let n=[],r=10;for(let t=0;t<e.length;t++){let i=e[t];if(i===`--seconds`){let n=e[++t];if(n===void 0)return{ok:!1,problem:`--seconds needs a number after it`};let i=Nr(Number(n));if(!i.ok)return{ok:!1,problem:`--seconds ${JSON.stringify(n)} ${i.problem}`};r=i.seconds}else if(i!==void 0&&!i.startsWith(`-`))n.push(i);else return{ok:!1,problem:`unexpected argument ${JSON.stringify(i)}`}}let[i,a,...o]=n;return i===void 0||a===void 0||o.length>0?{ok:!1,problem:`usage: cc-candybar record <session-id> <path> [--seconds N]`}:{ok:!0,args:{session:i,path:f(t,a),seconds:r}}}function Poe(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${Jr(e)}\n`,code:1};let{path:n,lines:r,answers:i,frames:a,daemonClosed:o}=e.value,s=`the daemon closed before ${t}s ran out`;return i+a===0?{stdout:``,stderr:o?`record: ${n}: ${s}, and nothing had been drawn, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered and no lane drew a frame in ${t}s, so there is nothing to replay: the session was idle, or its bar is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers, ${a} lane frames\n`,stderr:o?`record: ${s}: the file holds what came before.\n`:``,code:0}}async function Foe(e,t,n){let r=Noe(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return Poe(await Vr(e,()=>({kind:`record`,session:i,path:a,seconds:o}),{connectMs:200,budgetMs:o*1e3+2e3},e=>`recorded`in e?e.recorded:void 0),o)}const Ioe={connectMs:200,budgetMs:500};async function Loe(e,t,n){return Roe(t,await zoe(e,t),n.includes(`--json`))}function Roe(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
510
|
+
`:Boe(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${Jr(t)}\n`,code:1}}function zoe(e,t){return Vr(e,()=>({kind:`debug`,what:t}),Ioe,e=>`debug`in e?e.debug:void 0)}function Boe(e){switch(e.what){case`vars`:return Voe(e.vars);case`segments`:return Hoe(e.segments);case`config`:return Uoe(e.config);default:return e}}function Voe(e){if(e.length===0)return`no variables (DSL not active)
|
|
511
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${Goe(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${Woe(a.value)}${e}${o}`)}return t.join(`
|
|
512
512
|
`)+`
|
|
513
|
-
`}function
|
|
513
|
+
`}function Hoe(e){if(e.length===0)return`no segments (DSL not active)
|
|
514
514
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
515
515
|
`)+`
|
|
516
|
-
`}function
|
|
516
|
+
`}function Uoe(e){return e===null?`config: DSL not active
|
|
517
517
|
`:JSON.stringify(e,null,2)+`
|
|
518
|
-
`}function
|
|
518
|
+
`}function Woe(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Goe(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function Koe(){let e=Joe();return e===null?null:h.readFileSync(e,`utf-8`)}function qoe(){let e;try{e=Koe()}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 Joe(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(h.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const C9=5e3;function Yoe(e,t){return{ms:t,signal:it(e,t)}}function Xoe(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=aq(a,o);return{drawn:hZ(n,r,i,ese(t,a,e.at(-1)??null,s),c,a),opts:c}}const T9=`/home/tester`,E9=QZ(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),Zoe={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function Qoe(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 $oe(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]);return{lanes:{git:F({branch:`main`,status:`dirty`,aheadBehind:F({ahead:2,behind:1}),head:F(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:F(`abc1234`),operation:F(`rebase`),committedAt:F(n-780),stashCount:F(1),upstream:F(`origin/main`),repoName:F(`cc-candybar`),repoUrl:F(`https://github.com/promptctl/cc-candybar`),pullRequest:I}),usage:F({session:{cost:.39,calculatedCost:.39,officialCost:null,tokens:241400,tokenBreakdown:null}}),context:F({totalTokens:48487,percentage:76,contextLeftPercentage:24,maxTokens:1e6}),metrics:F({lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,nonPrompts:0,linesAdded:512,linesRemoved:88}),activity:I,tmuxSession:F(`work`),hostName:F(`tester-box`),hostUser:F(`tester`),cache:F(n+900),speed:I,autoCompact:F(4e5),sources:new Map(r.map(e=>[e,I]))},today:F({sums:eq(t,12.5,34e5),own:{}}),runs:new Map,faults:[]}}function ese(e,t,n,r){let i=Qoe(r),a=Q5(void 0,E9,$oe(e,r),{...I,at:r},r),{term:o,...s}=Dq(a,{hookData:i,hints:Zoe,home:T9},{effective:t,configFacts:{unsaved:1,resettable:cx(()=>!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:Nq(a.builtins.today,r)}}function tse(e,t){let n=aU(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function nse(e,n,r,i=t.cwd(),a=C9){let o=[],s=wP(i,r,e.host.home)??null,c=ar(e.host,e.home),l=eU(c,RU(Fn(e.home)).read(),i,i,s??void 0);o.push(...JH(l.repos));let u=s===null?tse(l,o):[$H(s)];if(s!==null){let e;try{e=h.statSync(s,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:s,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:s,message:`not a file`}}let d=sU(c,i,i);d!==null&&o.push(d);try{return{kind:`clean`,layers:u,warnings:o,rendered:await ase(e,n,u,{repo:l.repos.plugins},i,o,a)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&u.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Cy&&o.push(...e.warnings),{kind:`fatal`,layers:u,message:e instanceof Cy||e instanceof Error?e.message:String(e),warnings:o})}}async function rse(e,t,n,r,i,a,o=C9){let s=t.map(e=>e.path),c=SK(ar(e.host,e.home),t,JK,{warned:e=>i.push(...e)},{...n,cwd:r});kK(c.dropped);let{config:l}=c,u=new lw(e.clock),d=new _M({launcher:e.launcher,clock:e.clock}),f=new OM(d,u,l.globals.default_empty_value??``,new N1(A1));try{let t=$X(l,f,{cwd:r,links:{to:e.home.name,signer:u9(l9(Fn(e.home)))}});i.push(...t.loadWarnings);let n=qq(l,()=>null,()=>!1),p=Yoe(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 ise(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 Xoe(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=gZ(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 ase(e,t,n,r,i,a,o){let s=st(new Date(e.clock.now())),c=await rse(e,n,r,i,a,s,o),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=Nx(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=qq(l,t=>t===`preset`?e:null,()=>t),r;try{r=await ise(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 Mx(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(`
|
|
519
519
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
520
|
-
`));return d}finally{c.registry.dispose(),c.runs.close()}}function
|
|
521
|
-
`))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`,`/${
|
|
522
|
-
`));let l=o.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
520
|
+
`));return d}finally{c.registry.dispose(),c.runs.close()}}function D9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function ose(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${kP(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${YP(e.rendered)}\n`:``),stderr:D9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:D9(e.warnings)+`✗ ${kP(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 sse(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=sse(e),i=t.cwd();return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:ose(await nse(n,Nz(),OP(r.target,n.host,i).path,i),r.render)}const cse=/^[a-z][a-z0-9+.-]*:\/\//i,lse=/^[^@\s/]+@[^:\s/]+:/,use=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function dse(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function fse(e,t,n,r){let i=CP(t,e,n);if(r(i))return{kind:`path`,dir:i};if(cse.test(e)||lse.test(e))return{kind:`git`,url:e,shown:dse(e)};let a=use.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 pse(e,t){let n=s.join(e,IH),r=RH(n);if(`error`in r)throw Error(`${t}: could not list ${IH}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${IH}/<name>/${$V}`);return r.folders.map(e=>s.join(n,e,$V))}function mse(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 (${vt(a)})`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
|
|
521
|
+
`))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`,`/${IH}/`)}function hse({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=h.mkdtempSync(s.join(e.tmp,`cc-candybar-plugin-`));try{return mse(t,n.url,n.shown,s.join(i,`repo`)),r(s.join(i,`repo`))}finally{h.rmSync(i,{recursive:!0,force:!0})}}}}function gse(e){let t;try{t=h.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 _se(e,t,n,r){switch(r){case`updated`:h.renameSync(s.join(e,$V),s.join(t,$V));return;case`replaced`:h.renameSync(t,n),h.renameSync(e,t);return;case`installed`:h.renameSync(e,t);return}}function vse(e,t,n,r){let i=pse(e,n);h.mkdirSync(t,{recursive:!0});let a=h.mkdtempSync(s.join(t,`.install-`));try{let o=i.map(e=>{let t=s.join(a,s.basename(s.dirname(e)));h.mkdirSync(t);try{h.copyFileSync(e,s.join(t,$V))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),c=bK(o.map(e=>tH(s.join(e,$V),`plugins`)),JK,{root:e,git:!1},r);if(c.length>0)throw Error(c.map(e=>`${n}: ${s.join(IH,s.relative(a,e.path))} would not load: ${e.reason.split(a).join(s.join(n,IH))}`).join(`
|
|
522
|
+
`));let l=o.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:gse(r)}}),u=[];try{for(let{folder:e,name:t,target:n,placed:r}of l)_se(e,n,s.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:s.join(e,$V),placed:t}))}finally{h.rmSync(a,{recursive:!0,force:!0})}}function yse(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=fse(r,process.cwd(),t.host.home,e=>kn(Pn,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=hse(t,a,n=>vse(n,FH(ar(t.host,t.home)),e,t.host.home));for(let{path:t,placed:r}of n)console.log(`${r} plugin ${s.basename(s.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:`
|
|
523
523
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
524
|
-
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:
|
|
525
|
-
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:
|
|
526
|
-
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function
|
|
527
|
-
`;function
|
|
528
|
-
`);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
|
|
529
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?o7(e,a7(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([Ws(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,r7]),Ws(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,i7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:
|
|
524
|
+
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:ene(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 bse=[`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:bse.some(e=>(r[e]??``)!==``),tmux:_c(r),configEnv:EP(e,t),claudeConfigDir:ko(r,t),terminalEnv:mr(r)}}function P9(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function xse(e){let t=R4(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:Br(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 Sse=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},Cse=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 wse(e){let t=R4(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=F9(n?.postMortems,e=>Array.isArray(e)&&e.every(Sse)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&Cse(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=R4(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=>_ne.includes(e.role),Tse=e=>I9(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&vne.includes(e.rateLimits),`the rate-limit windows they carried`),Ese=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`),Dse=e=>I9(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&L9(e)&&uF.includes(e.frame),`what they drew and from which project`),Ose=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 z9(e){let t=R4(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:R9(e,`marks`,S0),clicked:R9(e,`clicked`,T0),postMortemsRead:R9(e,`postMortemsRead`,Y2)}}async function kse(e){let t=await L4(e);if(t.kind!==`ok`){let e={kind:`failed`,reason:Jr(t).split(`
|
|
525
|
+
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:xse(t.value),rateLimits:Tse(t.value),transcripts:Ese(t.value),frames:Dse(t.value),widths:Ose(t.value),serving:wse(t.value),stores:z9(t.value)}}const Ase=` (fix: click the settings menu (${na} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,jse=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${na} by default) › 🧰 tools › 🩺 doctor`;function Mse({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:Ase}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${jse}\n`)}function Nse({host:e,home:t,clock:n},r){let i={clock:n,locations:ar(e,t),sessionState:new N1(A1),storage:Cie,links:{to:t.name,signer:u9(l9(Fn(t)))},gates:Nz(),stateDir:Fn(t)},a=q5(r.projectDir,r.cwd,r.target.path,i),o=a.state??J5(r.cwd,a.repos.plugins,i);return o.registry.dispose(),{layers:a.layers,error:a.error??(o.dropped.map(e=>e.message).join(`
|
|
526
|
+
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function Pse(e,t,n){return n.kind===`failed`?n:$2(e,n.value.bundle,A0(t,n.value.clients).map(({client:e})=>e))}function Fse(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 Ise(e,t){return t.kind===`failed`?t:{kind:`ok`,value:A0(e,t.value).map(e=>e.transcript)}}function Lse(e,t){return t.kind===`failed`?t:{kind:`ok`,value:M0(e,t.value)}}function Rse(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:O4(e.sessionId,A0(e,t.value))}async function zse(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=k0(r.CLAUDE_CODE_SESSION_ID);s={...await k4(e,l,{projectDir:j0(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:OP(o,{env:r,home:e.home},i)},()=>null,c.serving,Fse(u,c.rateLimits,Ao(l.claudeConfigDir,e.home)),Ise(u,c.transcripts),u,Lse(u,c.frames),Rse(u,c.widths,l.termCols??null),c.stores),urlHandler:await r3(t),install:Pse(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=JF(s);return{stdout:c.map(Mse).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function Bse(){if(t.stderr.isTTY)return t.stderr;let e;try{e=C(`/dev/tty`,`r+`)}catch{return{}}let n=new ye(e),{columns:r}=n;return n.destroy(),{columns:r}}const B9=`Usage: cc-candybar doctor [config-file]
|
|
527
|
+
`;function Vse(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 Hse(e,n){let r=Vse(e);return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:await zse(f4(n.launcher,e=>Nse(n,e),n.host),c3(n.launcher,n),()=>kse(n),n.host.env,t.cwd(),Bse,r.configFile)}function Use(e){return!e.ok&&e.code!==`RENDER_FAILED`}function Wse(e,t,n,r,i,a){let o=null,s=null,c=e.dial(t),l=e=>{o===null&&(o=e,c.abandon(),s?.destroy(),a(e))},u={v:3,kind:`subscribe`,sessionId:n,lane:r};return c.settled.then(e=>{if(o!==null){e.ok&&e.conn.destroy();return}if(!e.ok){l({kind:`failed`,error:Error(e.failure.message)});return}let t=e.conn;s=t,t.on(`data`,Rr(e=>{let t=e;Use(t)?l({kind:`refused`,resp:t}):i(t)},e=>l({kind:`failed`,error:e}))),t.on(`error`,e=>l({kind:`failed`,error:e})),t.on(`close`,()=>l({kind:`closed-there`})),t.write(Ir(u))}),{close:()=>l({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 Gse(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=Wse(e.dialer,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=Gse(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&&Mi(e);let t=c;c=V9(c,`fault`),l(t,!0);return}}})};return u(),{close:()=>{s=!0,o?.(),a?.close()}}}function Kse(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function qse(e,n,r){let{values:i,tokens:a}=ne({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=Sb(i.lane);l===null&&(c(`--lane needs one of ${mb.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)=>{Kse(m,e)&&t(),m=e},g=async e=>{let i=await ti(r,e,o,s,{...N9(r.host,s,t.stderr),client:gr(`frames`,n)});i.kind!==`ok`&&(c(Jr(i)),j9(i).kick&&Mi(r))},_=e=>{p?.close(),p=H9(r,Vn(r.home),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 be({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 Jse(e){let t=e.replace(/\n+$/,``).split(`
|
|
528
|
+
`);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 Yse(e,t,n,r){let i=e.split(`
|
|
529
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?o7(e,a7(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([Ws(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,r7]),Ws(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,i7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:Yse(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 Xse(e){let{positionals:t}=(()=>{try{return ne({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 Zse(e,n){try{return await Qse(e,n),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function Qse(e,n){let{pane:r}=Xse(e),i=_c(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=Jse(u());e.rows!==t.stdout.rows&&!o.zoomed&&f(await Ws(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,Vn(n.home),e,`pane`,{frame:e=>r(j9(ei(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 ni(n,i.socket,r);e.kind===`ok`?(_(e.value),l=e.value===null?`waiting for pane ${r}'s statusline to render on ${Vn(n.home)}`:`waiting for pane ${r}'s bar`):(e.kind===`transient`&&(Mi(n),d=``),l=Jr(e))}g(),await rt(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 $se=(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=Ne(()=>`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 $se(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=rn(),{host:X9}=Y9;Me(!!X9.env.CC_CANDYBAR_DEBUG);const Z9=e=>e.some(e=>t.argv.includes(e));function Q9(){console.log(Bte);let e=cs(J9,X9),t=h.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${pb.statusline.label} yourself (a Bun-compiled Claude Code):\n ${hn(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const $9={install:async e=>{await ws(e,J9,Y9),t.exit(0)},"install-url-handler":async()=>{ys(J9,Y9),t.exit(0)},"url-handle":async e=>{await bs(e[0],Y9)},daemon:async()=>{Eoe(Y9)},"daemon-stats":async e=>{await q9(await F4(Y9,e))},record:async e=>{await q9(await Foe(Y9,e,t.cwd()))},frames:async()=>{await qse(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(yse(e,Y9))},schema:async()=>{await q9(qoe())},doctor:async e=>{await q9(await Hse(e,Y9))},"bar-pane":async e=>{t.exit(await Zse(e,Y9))},...Object.fromEntries(S8.map(e=>[e,async t=>{await q9(await Loe(Y9,e,t))}]))};async function ece(){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(vP.help)&&(Q9(),t.exit(0)),Z9(vP.version)&&(console.log(`cc-candybar ${wn}`),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
|
|
530
530
|
|
|
531
531
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
532
532
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -542,4 +542,4 @@ Add to ~/.claude/settings.json:
|
|
|
542
542
|
Run with --help for more options.
|
|
543
543
|
|
|
544
544
|
To test output manually:
|
|
545
|
-
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)),Pe(`Working directory: ${t.cwd()}`),Pe(`Process args:`,t.argv);let e=await a(t.stdin);Pe(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=
|
|
545
|
+
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)),Pe(`Working directory: ${t.cwd()}`),Pe(`Process args:`,t.argv);let e=await a(t.stdin);Pe(`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 ti(Y9,e,t.argv.slice(1),t.cwd(),{...N9(X9,t.cwd(),t.stderr),client:gr(`node`,J9)}));r.debug!==null&&Pe(r.debug),r.kick&&Mi(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})}}ece();export{};
|